append(element) { let newNode = newdoubleNode(element); if (!this.head) { this.head = newNode } else { let current = this.head while (current.next) { current = current.next } current.next = newNode newNode.previous = current } this.length += 1 }
find(item) { let current = this.head; while (current && current.element != item) { current = current.next } return current }
insert(newElement, item) { let current = this.find(item); let newNode = newdoubleNode(newElement); current.next.previous = newNode; newNode.next = current.next newNode.previou = current; current.next = newNode; this.length += 1
}
singleRemove(item) { let current = this.find(item); if (current.next) { current.previous.next = current.next; current.previous.previous = current.previous; current.previous.next.previous = current.previous current.previous = null; current.next = null }
}
3.双向链表
1
//双向链表的尾部指向头部
4.实现链表的反转
1 2 3 4 5 6 7 8 9 10 11 12 13 14
functionmyReverse(LinkedList) { let { head:current } = LinkedList; let next = null; let pre = null; while (current != null) { next = current.next; current.next = pre; pre = current; current = next; } list.head = pre }
6.测试
1 2 3 4 5 6 7
var list = newLinkedList() list.append(1) list.append(2) list.append(4) list.insert(2, 3) myReverse(list) console.log(list);