|
| 1 | +/* |
| 2 | + * @lc app=leetcode.cn id=707 lang=javascript |
| 3 | + * |
| 4 | + * [707] 设计链表 |
| 5 | + */ |
| 6 | + |
| 7 | +// @lc code=start |
| 8 | + |
| 9 | +var MyLinkedList = function() { |
| 10 | + this.head = null; |
| 11 | + this.count = 0; |
| 12 | +}; |
| 13 | + |
| 14 | +function ListNode(val, next) { |
| 15 | + this.val = val; |
| 16 | + this.next = next || null; |
| 17 | +} |
| 18 | + |
| 19 | +/** |
| 20 | + * @param {number} index |
| 21 | + * @return {number} |
| 22 | + */ |
| 23 | +MyLinkedList.prototype.get = function(index) { |
| 24 | + if (index < 0 || index >= this.count) { |
| 25 | + return -1; |
| 26 | + } |
| 27 | + return this.getElementAt(index).val; |
| 28 | +}; |
| 29 | + |
| 30 | +/** |
| 31 | + * @param {number} val |
| 32 | + * @return {void} |
| 33 | + */ |
| 34 | +MyLinkedList.prototype.addAtHead = function(val) { |
| 35 | + this.addAtIndex(0, val); |
| 36 | +}; |
| 37 | + |
| 38 | +/** |
| 39 | + * @param {number} val |
| 40 | + * @return {void} |
| 41 | + */ |
| 42 | +MyLinkedList.prototype.addAtTail = function(val) { |
| 43 | + this.addAtIndex(this.count, val); |
| 44 | +}; |
| 45 | + |
| 46 | +/** |
| 47 | + * @param {number} index |
| 48 | + * @param {number} val |
| 49 | + * @return {void} |
| 50 | + */ |
| 51 | +MyLinkedList.prototype.addAtIndex = function(index, val) { |
| 52 | + if (index < 0) { |
| 53 | + index = 0; |
| 54 | + } |
| 55 | + if (index >= 0 && index <= this.count) { |
| 56 | + const node = new ListNode(val); |
| 57 | + if (index === 0) { |
| 58 | + node.next = this.head; |
| 59 | + this.head = node; |
| 60 | + } else { |
| 61 | + // 找到待插入节点的前一个节点 |
| 62 | + const prev = this.getElementAt(index - 1); |
| 63 | + node.next = prev.next; |
| 64 | + prev.next = node; |
| 65 | + } |
| 66 | + this.count++; |
| 67 | + } |
| 68 | +}; |
| 69 | + |
| 70 | +/** |
| 71 | + * @param {number} index |
| 72 | + * @return {void} |
| 73 | + */ |
| 74 | +MyLinkedList.prototype.deleteAtIndex = function(index) { |
| 75 | + if (index >= 0 && index < this.count) { |
| 76 | + if (index === 0) { |
| 77 | + this.head = this.head.next; |
| 78 | + } else { |
| 79 | + const prev = this.getElementAt(index - 1); |
| 80 | + prev.next = prev.next.next; |
| 81 | + } |
| 82 | + this.count--; |
| 83 | + } |
| 84 | +}; |
| 85 | + |
| 86 | +MyLinkedList.prototype.getElementAt = function(index) { |
| 87 | + if (index >= 0 && index < this.count) { |
| 88 | + let curr = this.head; |
| 89 | + for (let i = 0; i < index && curr; i++) { |
| 90 | + curr = curr.next; |
| 91 | + } |
| 92 | + return curr; |
| 93 | + } |
| 94 | +} |
| 95 | + |
| 96 | +/** |
| 97 | + * Your MyLinkedList object will be instantiated and called as such: |
| 98 | + * var obj = new MyLinkedList() |
| 99 | + * var param_1 = obj.get(index) |
| 100 | + * obj.addAtHead(val) |
| 101 | + * obj.addAtTail(val) |
| 102 | + * obj.addAtIndex(index,val) |
| 103 | + * obj.deleteAtIndex(index) |
| 104 | + */ |
| 105 | +// @lc code=end |
| 106 | + |
0 commit comments