優勢:添加或者移除元素的時候不須要移動其餘元素。只須要找到加入的節點,斷開並插入一個元素(修改引用)javascript
function LinkedList() { let Node = function (element) {// 輔助類,包含一個element屬性即具體的值,以及一個next屬性即指向下一個節點的引用 this.element = element; this.next = null; }; let length = 0; let head = null; /** * 向列表尾部添加一個新的項 * @param element */ this.append = function (element) { let node = new Node(element), current; if (head === null) { head = node; } else { current = head; // 循環列表找到最後一項 while (current.next) { current = current.next } // 將最後一項的引用指向新元素(將最後一項的next指向node,創建新鏈接) current.next = node; } length++;// 更新列表的長度 }; /** * 向列表的特定位置插入一個新的項 * @param position * @param element */ this.insert = function (position, element) { if (position > -1 && position < length) { let node = new Node(element); let current = head, previous, index = 0; if (position === 0) { head = node; node.next = current } else { while (index++ < position) { previous = current; current = current.next } previous.next = node; node.next = current } length++; return true } else { return false } }; /** * 從列表的特定位置移出一項 * @param position */ this.removeAt = function (position) { // 檢查越界值 if (position > -1 && position < length) {// 驗證該位置是否有效 // current是對要移出元素的引用 // previous是對要移出的元素前一個元素的引用 let current = head, index = 0, previous; // 移出第一項 if (position === 0) { head = current.next; } else { while (index++ < position) { previous = current; current = current.next } // 將previous與current的下一項連接起來:這樣跳過current,從而實現移出,垃圾收集 previous.next = current.next } length--; return current.element } else { return null } }; /** * 從列表移出一項 * @param element */ this.remove = function (element) { }; /** * 返回元素在列表中的索引 * @param element */ this.indexOf = function (element) { let current = head, index = 0; while(current){ if(element === current.element){// 斷定條件須要優化,對於應用類型要斷定值相等 return index; } index++; current = current.next } return -1 }; this.isEmpty = function () { }; this.size = function () { }; this.getHead = function () { }; /** * 因爲使用Node輔助類,因此要重寫繼承自默認對象的toString方法 */ this.toString = function () { let current = head, string = ''; while (current) { string += current.element + (current.next ? 'n' : ''); current = current.next } return string }; this.print = function () { } }