# Leetcode 838 Solution

## Solution

``````class MyListNode {
public:
int val;
MyListNode* next;

MyListNode() {
val = 0;
next = NULL;
}
};

MyListNode list;

public:
/** Initialize your data structure here. */
}

/** 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. */
}

/** Append a node of value val to the last element of the linked list. */
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;
}
}
};

/**