You are on page 1of 3

/**

* Initialize your data structure here.


*/
var MyLinkedList = function() {
this.head = null;
this.val = null;
this.next = null;
return this;
};

/**
* Get the value of the index-th node in the linked list. If the index is invalid,
return -1.
* @param {number} index
* @return {number}
*/
MyLinkedList.prototype.get = function(index) {
var cur = this.head;
for(var i = 0 ; i < index ; i++) {
if (!cur)
return -1;
if (cur.next) {
cur = cur.next;
} else {
return -1;
}
}
return cur ? cur.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.
* @param {number} val
* @return {void}
*/
MyLinkedList.prototype.addAtHead = function(val) {
var oldHead = this.head;
this.head = {
val : val,
next : oldHead
}
};

/**
* Append a node of value val to the last element of the linked list.
* @param {number} val
* @return {void}
*/
MyLinkedList.prototype.addAtTail = function(val) {
var cur = this.head;
if (cur) {
while(cur.next) {
cur = cur.next;
}
cur.next = {
val : val,
next : null
}
} else {
this.head = {
val : val,
next : null
}
}
};

/**
* 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.
* @param {number} index
* @param {number} val
* @return {void}
*/
MyLinkedList.prototype.addAtIndex = function(index, val) {

var prev, cur = this.head;


for (var i = 0 ; i < index ; i++) {
if (!cur)
return;
prev = cur;
cur = prev.next;
}

var add = {
val : val,
next : cur
}
if (prev)
prev.next = add;
else
this.head = add;
};

/**
* Delete the index-th node in the linked list, if the index is valid.
* @param {number} index
* @return {void}
*/
MyLinkedList.prototype.deleteAtIndex = function(index) {
var prev, cur = this.head;
for (var i = 0 ; i < index ; i++) {
prev = cur;
cur = prev.next;
if (!cur)
return;
}
if (prev)
prev.next = cur.next;
else
this.head = cur.next;
};

/**
* Your MyLinkedList object will be instantiated and called as such:
* var obj = Object.create(MyLinkedList).createNew()
* var param_1 = obj.get(index)
* obj.addAtHead(val)
* obj.addAtTail(val)
* obj.addAtIndex(index,val)
* obj.deleteAtIndex(index)
*/

You might also like