/** * Get the value of the index-th node in the linked list. If the index is invalid, return -1. * 返回的是节点(包含内容与下标) * @param {number} index * @return {number} */ MyLinkedList.prototype.getNode = function(index) { // index超过size或者小于0直接返回-1(没有) if(index < 0 || index >= this._size) returnnull; // 创建虚拟头节点 let cur = newLinkNode(0, this._head); // 0 -> head // 一直遍历链表,直到第index位 while(index-- >= 0) { cur = cur.next; } return cur; }; // 给下标,获取内容 MyLinkedList.prototype.get = function(index) { if(index < 0 || index >= this._size) return -1; // 获取当前节点 returnthis.getNode(index).val; };
/** * Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. * @param {number} val * @return {void} */ // 从头部增加链表节点 MyLinkedList.prototype.addAtHead = function(val) { // 先新建一个链表,val是头,this._head作为他的next const node = newLinkNode(val, this._head); this._head = node; // 记录大小的更改 this._size++; if(!this._tail) { this._tail = node; } };
/** * Append a node of value val to the last element of the linked list. * @param {number} val * @return {void} */ // 从尾部新增链表节点 MyLinkedList.prototype.addAtTail = function(val) { // 新建一个链表 const node = newLinkNode(val, null); this._size++; // 如果有尾巴,好说 if(this._tail) { this._tail.next = node; this._tail = node; return; } // 如果没尾巴,更好说 this._tail = node; this._head = node; };
/** * Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted. * @param {number} index * @param {number} val * @return {void} */ MyLinkedList.prototype.addAtIndex = function(index, val) { if(index > this._size) return; if(index <= 0) { this.addAtHead(val); return; } if(index === this._size) { this.addAtTail(val); return; } // 获取目标节点的上一个的节点 const node = this.getNode(index - 1); node.next = newLinkNode(val, node.next); this._size++; };
/** * Delete the index-th node in the linked list, if the index is valid. * @param {number} index * @return {void} */ 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--; };
// MyLinkedList.prototype.out = function() { // let cur = this._head; // const res = []; // while(cur) { // res.push(cur.val); // cur = cur.next; // } // }; /** * 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) */