一、题目
二、题解
class LinkNode { constructor ( val, next ) { this . val= val this . next= next }
}
var MyLinkedList = function ( ) { this . size= 0 this . head= null this . tail= null
} ;
MyLinkedList . prototype. get = function ( index ) { if ( index < 0 || index >= this . size) return - 1 ; return this . getNode ( index) . val;
} ;
MyLinkedList . prototype. addAtHead = function ( val ) { const node = new LinkNode ( val, this . head) ; this . head = node; this . size++ ; if ( ! this . tail) { this . tail = node; }
} ;
MyLinkedList . prototype. addAtTail = function ( val ) { const node = new LinkNode ( val, null ) ; this . size++ ; if ( this . tail) { this . tail. next = node; this . tail = node; return ; } this . tail = node; this . head = node;
} ;
MyLinkedList . prototype. getNode = function ( index ) { if ( index < 0 || index >= this . size) return null ; let cur = new LinkNode ( 0 , this . head) ; while ( index-- >= 0 ) { cur = cur. next; } return cur;
} ;
MyLinkedList . prototype. addAtIndex = function ( index, val ) { if ( index> this . size) return ; if ( index=== this . size) { this . addAtTail ( val) return ; } if ( index<= 0 ) { this . addAtHead ( val) return ; } const node = this . getNode ( index- 1 ) node. next= new LinkNode ( val, node. next) this . size++ ;
} ;
MyLinkedList . prototype. deleteAtIndex = function ( index ) { if ( index < 0 || index >= this . size) return ; if ( index === 0 ) { this . head = this . head. next; if ( index === this . size - 1 ) { this . tail = this . head} this . size-- ; return ; } const node = this . getNode ( index - 1 ) ; node. next = node. next. next; if ( index === this . size - 1 ) { this . tail = node; } this . size-- ;
} ;