標籤:current nbsp previous return rem 對象 測試 例子 blog
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 c1num.remove("b1");num.display();// a1 c1
JS實現一個基於對象的鏈表