Skip to content

Instantly share code, notes, and snippets.

@FloydanTheBeast
Created September 16, 2020 09:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FloydanTheBeast/adb16d57961e7a3c094981ef38f41da9 to your computer and use it in GitHub Desktop.
Save FloydanTheBeast/adb16d57961e7a3c094981ef38f41da9 to your computer and use it in GitHub Desktop.
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