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
| class Node { constructor(value) { this._value = value; this.next = null; }
getValue() { return this._value; } }
class LinkedList { constructor() { this._head = null; this._size = 0; }
getSize() { return this._size; }
toString() { if (this._head === null) { return ''; } let result = ''; let curr = this._head; while (curr !== null) { result += curr.getValue() + ', '; curr = curr.next; } return result; }
append(value) { if (this._head === null) { this._head = new Node(value); this._size++; return; } let curr = this._head; while (curr) { if (curr.next === null) { curr.next = new Node(value); this._size++; } curr = curr.next; } }
shift() { if (this._size === 0) { return null; } let head = this._head; this._head = head.next; this._size--; return head.getValue(); }
getItem(index) { if (this._size === 0) { return null; } if (index < 0 || index >= this._size) { return console.log('Index out of range'); } if (index === 0) { return this._head.getValue(); } let curr = this._head; for (let i = 0; i < index; i++) { curr = curr.next; } return curr.getValue(); } }
|