struct Node
{
Node* prev;
Node* next;
int val;
};
class MyLinkedList {
public:
/** Initialize your data structure here. */
MyLinkedList() {
_head = new Node();
_tail = new Node();
_head->next = _tail;
_tail->prev = _head;
_len=0;
}
/** 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 >= _len) return -1;
Node* ptr = _head->next;
for(int i=0; i<index; ++i)
{
ptr = ptr->next;
}
return ptr->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* ptr = new Node();
ptr->val = val;
ptr->prev = _head;
ptr->next = _head->next;
_head->next->prev = ptr;
_head->next = ptr;
_len++;
}
/** Append a node of value val to the last element of the linked list. */
void addAtTail(int val) {
Node* ptr = new Node();
ptr->val = val;
ptr->prev = _tail->prev;
ptr->next = _tail;
_tail->prev->next = ptr;
_tail->prev = ptr;
_len++;
}
/** 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) {
Node* ptr = _head;
Node* newItem = new Node();
if(index>_len) return;
for(int i=0; i<index; ++i) ptr=ptr->next;
newItem->val = val;
newItem->prev = ptr;
newItem->next = ptr->next;
ptr->next->prev = newItem;
ptr->next = newItem;
_len++;
return;
}
/** Delete the index-th node in the linked list, if the index is valid. */
void deleteAtIndex(int index) {
if(index >= _len) return;
Node* ptr = _head->next;
for(int i=0; i<index; ++i) ptr=ptr->next;
ptr->prev->next = ptr->next;
ptr->next->prev = ptr->prev;
_len--;
}
private:
Node* _head;
Node* _tail;
int _len;
};
/**
* 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);
*/