function Node(element) { this.element = element; this.next = null; this.previous = null; } function LList() { this.head = new Node("head"); this.find = find; this.insert = insert; this.display = display; this.remove = remove; this.findLast = findLast; this.dispReverse = dispReverse; } function find(item) { var currNode = this.head; while (currNode.element != item) { currNode = currNode.next; } return currNode; } function insert(newElement, item) {//在item后面插入新节点 var newNode = new Node(newElement); var current = this.find(item); newNode.next = current.next; newNode.previous = current; current.next = newNode; } function display() { var currNode = this.head; while (!(currNode.next == null)) { document.write(currNode.next.element + " "); currNode = currNode.next; } } function remove(item) { var currNode = this.find(item); if ((currNode.element != null) && (currNode.next == null)) { currNode.previous.next = null; currNode.previous = null; } else if (currNode.element != null) { currNode.previous.next = currNode.next;//当前节点的前一个节点的链接指向当前节点的后一个节点 currNode.next.previous = currNode.previous;//当前节点的后一个节点的链接指向当前节点的前一个节点 currNode.next = null;//将当前节点的后向指针置空 currNode.previous = null;//将当前节点的前向指针置空 } } function findLast() { var currNode = this.head; while (currNode.next != null) {//针对于只有一个空节点的情况 currNode = currNode.next; } return currNode; } //反序显示双向链表中的元素 function dispReverse() { var currNode = this.head; currNode = this.findLast(); while (currNode.previous != null) {//head节点的前向指针指向null document.write(currNode.element + " "); currNode = currNode.previous; } } var cities = new LList(); cities.insert("Conway", "head"); cities.insert("Russellville", "Conway"); cities.insert("Carlisle", "Russellville"); cities.insert("Alma", "Carlisle"); cities.display(); document.write("<br />"); cities.remove("Alma"); cities.display(); document.write("<br />"); cities.dispReverse(); document.write("<br />"); cities.remove("Conway"); cities.display();