classMyLinkedList { public: /** Initialize your data structure here. */ structLinkedNode { int val; LinkedNode* next; LinkedNode(int val):val(val),next(nullptr){} LinkedNode(int val,LinkedNode* next1):val(val),next(next1){} };
MyLinkedList(){ dummyHead = newLinkedNode(0); _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 > (_size - 1) || index < 0) return-1; LinkedNode* top = dummyHead->next; while(index--) top = top->next; return top->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){ LinkedNode *second = dummyHead->next; LinkedNode* addNode = newLinkedNode(val,second); dummyHead->next = addNode; _size++; }
/** Append a node of value val to the last element of the linked list. */ voidaddAtTail(int val){ LinkedNode* newNode=newLinkedNode(val); LinkedNode* tail = dummyHead; while(tail->next != nullptr){ tail = tail->next; } tail -> next = newNode; _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; } LinkedNode * indexNode = dummyHead; while(index--){ indexNode = indexNode->next; } LinkedNode* tmp = newLinkedNode(val,indexNode->next); indexNode->next = tmp; _size++; }
/** Delete the index-th node in the linked list, if the index is valid. */ voiddeleteAtIndex(int index){ if (index >= _size || index < 0) { return; } LinkedNode* indexNode = dummyHead; while(index--){ indexNode = indexNode->next; } LinkedNode* tmp = indexNode->next; indexNode->next = indexNode->next->next; delete tmp; _size--; } private: int _size; LinkedNode* dummyHead; };
/** * Your MyLinkedList object will be instantiated and called as such: * MyLinkedList* obj = new MyLinkedList(); * int param_1 = obj->get(index); * obj->addAtHead(val); * obj->addAtTail(val); * obj->addAtIndex(index,val); * obj->deleteAtIndex(index); */