1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
| class LinkedNode { constructor(value) { this.value = value this.next = null } }
class LinkedList { constructor() { this.count = 0 this.head = null }
addAtTail(value) { const node = new LinkedNode(value) if (this.count === 0) { this.head = node } else { let cur = this.head while (cur.next != null) { cur = cur.next } cur.next = node } this.count++ }
addAtHead(value) { const node = new LinkedNode(value) if (this.count === 0) { this.head = node } else { node.next = this.head this.head = node } this.count++ }
get(index) { if (this.count === 0 || index < 0 || index >= this.count) { return } let current = this.head for (let i = 0; i < index; i++) { current = current.next } return current }
addAtIndex(value, index) { if (this.count === 0 || index >= this.count) { return } if (index <= 0) { return this.addAtHead(value) } const prev = this.get(index - 1) const next = prev.next
const node = new LinkedNode(value) prev.next = node node.next = next
this.count++ }
removeAtIndex(index) { if (this.count === 0 || index < 0 || index >= this.count) { return } if (index === 0) { this.head = this.head.next } else { const prev = this.get(index - 1) prev.next = prev.next.next } this.count-- } }
const l = new LinkedList() l.addAtTail('a') l.addAtTail('b') l.addAtTail('c')
|