function Node(element) { this.element = element;// element 用来保存节点上的数据 this.next = null;//用来保存指向下一个节点的链接 } function LList() { this.head = new Node("head"); this.find = find; this.insert = insert; //this.remove = remove;remove()若是未定义会出错!!必须注释掉 this.findPrevious = findPrevious; this.remove = remove; this.display = display; } function find(item) { var currNode = this.head; while (currNode.element != item) { currNode = currNode.next; } return currNode; } function insert(newElement, item) { //在item节点后插入newElement新节点 var newNode = new Node(newElement);//插入元素必先创建节点 var current = this.find(item); //添加元素不需要考虑item不存在的情况,因为当item不存在时,可在链表末尾添加 newNode.next = current.next;//用链表的思想去考虑,不要从赋值的角度考虑 //node.next()可看作指向下一个节点的链接&&下一个节点 //理解为链接指向新节点,newNode.next链接指向current.next节点 current.next = newNode;//此处断开原链接 } function display() { var currNode = this.head; while (!(currNode.next == null)) { document.write(currNode.next.element + ""); currNode = currNode.next; } } var cities = new LList(); cities.insert("Conway", "head"); cities.insert("Russellville", "Conway"); cities.insert("Alma", "Russellville"); cities.display(); document.write("*********" + ""); function findPrevious(item) { //删除元素需要找到该元素前面的节点 var currNode = this.head; while ((currNode.next.element != item)) { currNode = currNode.next; } return currNode; } function remove(item) { var prevNode = this.findPrevious(item); if (prevNode.next != null) { prevNode.next = prevNode.next.next; } } cities.insert("lelei", "Alma"); cities.remove("Alma"); cities.display(); /* 上述程序运行结果如下: Conway Russellville Alma ********* Conway Russellville lelei*/
关于添加节点的图示理解: