class LinkNode { val: any next: LinkNode | null constructor(val?: any, next?: LinkNode | null) { this.val = val this.next = next || null } }
/** * 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) */ class MyLinkedList { size: number head: LinkNode | null constructor() { this.size = 0 this.head = null }
get(index: number): number { let cur = this.head while (cur && index--) cur = cur.next return cur ? cur.val : -1 }
addAtTail(val: number): void { if (this.size === 0) { this.addAtHead(val) return } let cur = this.head while (cur.next) cur = cur.next cur.next = new LinkNode(val) this.size++ }
addAtIndex(index: number, val: number): void { if (index > this.size) return if (index <= 0) { this.addAtHead(val) return } if (index === this.size) { this.addAtTail(val) return } let cur = this.head while (index-- > 1) cur = cur.next cur.next = new LinkNode(val, cur.next) this.size++ }
deleteAtIndex(index: number): void { if (index < 0 || index >= this.size) return let dummyHead = new LinkNode() dummyHead.next = this.head let cur = dummyHead while (index--) cur = cur.next cur.next = cur.next.next this.head = dummyHead.next this.size-- } }