MyLinkedList.prototype.get=function(index){if(index <0|| index >this.size -1){return-1;}var cur =this.dummy.next;while(index){
cur = cur.next;
index--;}return cur.val;};
MyLinkedList.prototype.addAtTail=function(val){var tailNode =newListNode(val);var cur =this.dummy;while(cur.next !=null){
cur = cur.next;}
cur.next = tailNode;this.size++;};
(4) 第n个节点前插入节点
新建待插入节点newNode。
cur指向哨兵节点,cur向后移动n次后,指向第n - 1个节点。
① newNode节点指向第n个节点。
② 第n - 1个节点指向newNode节点。
链表长度+1。
MyLinkedList.prototype.addAtIndex=function(index, val){if(index <0|| index >this.size){return;}var newNode =newListNode(val);var cur =this.dummy;while(index){
cur = cur.next;
index--;}
newNode.next = cur.next;
cur.next = newNode;this.size++;};
(5) 删除第n个节点
cur指向哨兵节点,cur向后移动n次后,指向第n - 1个节点。
① 第n - 1个节点指向第n + 1个节点(第n个节点的下一个节点)。
链表长度-1。
MyLinkedList.prototype.deleteAtIndex=function(index){if(index <0|| index >this.size -1){return;}var cur =this.dummy;while(index){
cur = cur.next;
index--;}
cur.next = cur.next.next;this.size--;};
完整代码
functionListNode(val, next){this.val =(val===undefined?0: val);this.next =(next===undefined?null: next);}varMyLinkedList=function(){this.size =0;this.dummy =newListNode();};/**
* @param {number} index
* @return {number}
*/MyLinkedList.prototype.get=function(index){if(index <0|| index >this.size -1){return-1;}var cur =this.dummy.next;while(index){
cur = cur.next;
index--;}return cur.val;};/**
* @param {number} val
* @return {void}
*/MyLinkedList.prototype.addAtHead=function(val){var headNode =newListNode(val);
headNode.next =this.dummy.next;this.dummy.next = headNode;this.size++;};/**
* @param {number} val
* @return {void}
*/MyLinkedList.prototype.addAtTail=function(val){var tailNode =newListNode(val);var cur =this.dummy;while(cur.next !=null){
cur = cur.next;}
cur.next = tailNode;this.size++;};/**
* @param {number} index
* @param {number} val
* @return {void}
*/MyLinkedList.prototype.addAtIndex=function(index, val){if(index <0|| index >this.size){return;}var newNode =newListNode(val);var cur =this.dummy;while(index){
cur = cur.next;
index--;}
newNode.next = cur.next;
cur.next = newNode;this.size++;};/**
* @param {number} index
* @return {void}
*/MyLinkedList.prototype.deleteAtIndex=function(index){if(index <0|| index >this.size -1){return;}var cur =this.dummy;while(index){
cur = cur.next;
index--;}
cur.next = cur.next.next;this.size--;};/**
* Your MyLinkedList object will be instantiated and called as such:
* var obj = new MyLinkedList()
* var param_1 = obj.get(index)
* obj.addAtHead(val)
* obj.addAtTail(val)
* obj.addAtIndex(index,val)
* obj.deleteAtIndex(index)
*/