資料結構與演算法JavaScript描述讀書筆記(js實現連結串列-雙向連結串列)
阿新 • • 發佈:2018-11-04
雙向連結串列
雙向連結串列的 remove() 方法比單向連結串列的效率更高,因為不需要再查詢前驅節點了
//建立建構函式建立節點 function Node(element){ this.element = element; this.next = null; this.previous = null; this.findLast = findLast; this.disPreverse = disPreverse; } //連結串列的建構函式 function LList(){ this.head = new Node('head'); this.insert = insert; this.remove = remove; this.display = display; this.find = find; } function insert(newElement,item){ var cur = this.find(item); var node = new Node(newElement); if(cur == null){ alert('沒有找到插入位置'); }else{ node.next = cur.next; node.previous = cur; cur.next = node;} } function find(item){ var cur = this.head; while(cur.element != item){ cur = cur.next; } return cur; } function display() { var cur = this.head; var str = ''; while (cur.next != null){ str += cur.next.element+'->'; cur = cur.next; } return str; } function remove(item){ var cur = this.find(item); if(cur.next != null){ cur.previous.next = cur.next; cur.next.previous = cur.previous; cur.next = null; cur.previous = null; }else{ //注意,當節點的後繼為null時不要設定cur.next.previous = cur.previous //因為雙向連結串列中null時沒有前驅的,不能設定null的前驅cur.previous.next = null; } } //查詢最後一個節點 function findLast(){ var cur = this.head; while(cur.next != null){ cur = cur.next; } return cur; } //反序輸出節點 function disPreverse(){ //注意,findLast()即使沒有引數也要帶括號 //如果不帶括號,last則是一個function物件 var last = this.findLast(); //console.log(last); var str = ''; while(last.previous != null){ str += last.element+'->'; last = last.previous; } return str; }