雙向連結串列實現查詢、刪除、插入、末尾增加
阿新 • • 發佈:2020-10-29
雙向連結串列可以從前往後查詢或者從後往前查詢,提高了查詢效率。需要儲存兩個方向的指標,佔用了更大的空間。
let DoubleNode = function(element){ this.element = element; this.next = null; this.prior = null; } class DobuleLinkedList { constructor() { this.length = 0; this.head = null; this.tail = null; } // 獲取某位置的結點getElementAt(position) { if(position < 0 || position >= this.length){ return; } let current; if(position <= this.length/2){ current = this.head; for(let i = 0; i < position; i++){ current = current.next; } }else{ current = this.tail; for(let i = this.length - 1; i > position; i++){ current = current.prior; } } return current; } append(element) { let node = new DoubleNode(element); if(this.head === null){this.head = node; }else{ let origin = this.getElementAt(this.length - 1); origin.next = node; node.prior = origin; } this.tail = node; this.length++; } // 在某位置插入1個結點 insert(position, element) { let node = new DoubleNode(element); if(position < 0 || position > this.length){ return; }else{ if(this.head === null){ this.head = node; this.tail = node; }else{ // 插在頭結點 if(position === 0){ node.next = this.head; this.head.prior = node; this.head = node; }else{ let origin = this.getElementAt(position - 1); node.prior = origin; if(origin.next){ // 插在中間 node.next = origin.next; origin.next.prior = node; origin.next = node; }else{ // 插在最後一位 node.next = null; origin.next = node; this.tail = node; } } } this.length++; } } // 在某位置刪除1個結點 delete(position) { if(position < 0 || position > this.length){ return; }else{ if(position === 0){ this.head = this.head.next; this.head.prior = null; }else{ let current = this.getElementAt(position); // 刪除中間位 if(current.next){ current.prior.next = current.next; current.next.prior = current.prior; }else{ // 刪除最後一位 current.prior.next = null; this.tail = current.prior; } } this.length--; } } }