Leetcode 838 Solution
This article provides solution to leetcode question 838 (design-linked-list)
Access this page by simply typing in "lcs 838" in your browser address bar if you have bunnylol configured.
Leetcode Question Link
https://leetcode.com/problems/design-linked-list
Solution
class MyListNode {
public:
int val;
MyListNode* next;
MyListNode() {
val = 0;
next = NULL;
}
};
class MyLinkedList {
MyListNode list;
public:
/** Initialize your data structure here. */
MyLinkedList() {
}
/** 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 < 0)
return -1;
MyListNode* node = &list;
for (int i = 0; i <= index; i++)
{
if (node == NULL)
return -1;
node = node->next;
}
return node ? node->val : -1;
}
/** 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) {
addAtIndex(0, val);
}
/** Append a node of value val to the last element of the linked list. */
void addAtTail(int val) {
MyListNode* prev = &list;
MyListNode* curr = prev->next;
while (curr)
{
prev = curr;
curr = curr->next;
}
auto newNode = new MyListNode();
newNode->val = val;
prev->next = newNode;
}
/** 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 < 0)
return;
MyListNode* prev = &list;
MyListNode* node = prev->next;
for (int i = 0; i < index; i++)
{
if (node == NULL)
return;
prev = node;
node = node->next;
}
auto newNode = new MyListNode();
newNode->val = val;
newNode->next = prev->next;
prev->next = newNode;
}
/** Delete the index-th node in the linked list, if the index is valid. */
void deleteAtIndex(int index) {
if (index < 0)
return;
MyListNode* prev = &list;
MyListNode* node = prev->next;
for (int i = 0; i < index; i++)
{
if (node == NULL)
return;
prev = node;
node = node->next;
}
if (node)
{
prev->next = node->next;
delete node;
}
}
};
/**
* 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);
*/