classMyLinkedList { private: ListNode * dummy = nullptr, * end = nullptr; int size; public: /** Initialize your data structure here. */ MyLinkedList() { dummy = newListNode(); end = dummy; size = 0; }
/** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */ intget(int index){ if(index < 0 || index >= size) { return-1; } ListNode * cur = dummy; //走 index + 1 步 for(int i = 0; i <= index; i++) { cur = cur->next; } return cur->val; }
/** Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. */ voidaddAtHead(int val){ ListNode * node = newListNode(val); //如果是链表为空,则修改end指针 if(dummy == end) { end = node; } node->next = dummy->next; dummy->next = node; size++; }
/** Append a node of value val to the last element of the linked list. */ voidaddAtTail(int val){ ListNode * node = newListNode(val); end->next = node; end = end->next; size++; }
/** Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted. */ voidaddAtIndex(int index, int val){ if(index > size) { return; } if(index <= 0) { //索引小于等于0,添加到头部 addAtHead(val); } elseif(index == size) { //index == size,则添加到最后 addAtTail(val); } else { ListNode * pre = dummy; for(int i = 0; i < index; i++) { pre = pre->next; } ListNode * node = newListNode(val); node->next = pre->next; pre->next = node; size++; } }
/** Delete the index-th node in the linked list, if the index is valid. */ voiddeleteAtIndex(int index){ if(index < 0 || index >= size) { return; } ListNode * pre = dummy; for(int i = 0; i < index; i++) { pre = pre->next; } // 如果要删除节点为尾节点,则要修改end指针 if(index == size - 1) { end = pre; } pre->next = pre->next->next; size--; } };