JS实现一个基于对象的链表
/*JS实现一个基于对象的链表*/ function Node(element){ this.element = element;//节点存储的元素 this.next = null;//节点指向的下一个节点,这里先设置为空 } function LList(){ this.head = new Node("head");//生成一个头节点 this.find = find;//在链表中找到某个节点 this.insert = insert;//在链表中某个元素后面插入某个节点元素 this.display = display;//在将链表中的节点元素显示出来 this.findPrevious = findPrevious;//找到某个节点的上一个节点 this.remove = remove;//删除某个节点 } function remove(item) { var prevNode = this.findPrevious(item); if (!(prevNode.next == null)) { prevNode.next = prevNode.next.next; } } function findPrevious(item) { var currNode = this.head; while (!(currNode.next == null) && (currNode.next.element != item)) { currNode = currNode.next; } return currNode; } function display() { var currNode = this.head; var nodestr = ""; while (!(currNode.next == null)) { nodestr +=" "+currNode.next.element; currNode = currNode.next; } console.log(nodestr); } function find(item) { var currNode = this.head; while (currNode.element != item) { currNode = currNode.next; } return currNode; } function insert(newElement, item) { var newNode = new Node(newElement); var current = this.find(item); newNode.next = current.next; current.next = newNode; } /*测试例子*/ var num = new LList(); num.insert("a1","head"); num.insert("b1","a1"); num.insert("c1","b1"); num.display();// a1 b1 c1 num.remove("b1"); num.display();// a1 c1
时间: 2024-10-02 18:55:49