Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Algorithms and data structures
struct Node {
int val;
Node *next;
Node(int x) : val(x), next(NULL) {}
};
class MyLinkedList {
public:
int length;
Node *head;
/** Initialize your data structure here. */
MyLinkedList() {
length = 0;
head = NULL;
}
/** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */
int get(int index) {
if (index >= length || index < 0)
return -1;
Node *currNode = head;
for (int i = 0; i < index; i++) currNode = currNode->next;
return currNode->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. */
void addAtHead(int val) {
Node *copiedHead = head;
head = new Node(val);
head->next = copiedHead;
++length;
}
/** Append a node of value val to the last element of the linked list. */
void addAtTail(int val) {
Node *currNode = head;
for (int i = 0; i < length - 1; i++) currNode = currNode->next;
currNode->next = new Node(val);
++length;
}
/** 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. */
void addAtIndex(int index, int val) {
if (index > length || index < 0)
return;
if (index == 0)
return addAtHead(val);
if (index == length)
return addAtTail(val);
Node *currNode = head;
for (int i = 0; i < index - 1; i++) currNode = currNode->next;
Node *newNode = new Node(val);
newNode->next = currNode->next;
currNode->next = newNode;
++length;
cout << length;
}
/** Delete the index-th node in the linked list, if the index is valid. */
void deleteAtIndex(int index) {
if (index >= length || index < 0)
return;
if (index == 0) {
head = head->next;
--length;
return;
}
Node *currNode = head;
for (int i = 0; i < index - 1; i++) currNode = currNode->next;
currNode->next = currNode->next->next;
--length;
}
};
/**
* 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);
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.