使用 JavaScript 將元素插入雙向連結串列
我們需要建立一個函式 insert(data, position),該函式在連結串列的給定位置插入資料。我們將執行以下步驟:
- 建立一個新的節點
- 檢查列表是否為空。如果是,則將節點新增到頭部和尾部並返回。
- 如果不是,我們將使用 currElem 迭代到我們想要插入的位置。我們透過使 currElem 等於 currElem.next 來迭代連結串列。
現在,我們將以以下方式更改連結:
- 使新節點指向列表中的下一個節點
- 使下一個節點的上一個指向新節點
- 使我們的節點指向前一個節點
- 使前一個節點的下一個指向新節點
最後,我們斷開 currElem 與列表其餘部分的連結,並使其指向我們建立的節點。現在,該節點位於列表中給定位置。
這是一個相同的示例:
現在讓我們看看我們將如何實現它:
示例
insert(data, position = this.length) { let node = new this.Node(data); this.length++; // List is currently empty if (this.head === null) { this.head = node; this.tail = node; return this.head; } // Insertion at head if (position == 0) { node.prev = null; node.next = this.head; this.head.prev = node; this.head = node; return this.head; } let iter = 1; let currNode = this.head; while (currNode.next != null && iter < position) { currNode = currNode.next; iter++; } // Make new node point to next node in list node.next = currNode.next; // Make next node's previous point to new node if (currNode.next != null) { currNode.next.prev = node; } // Make our node point to previous node node.prev = currNode; // Make previous node's next point to new node currNode.next = node; // check if inserted element was at the tail, if yes then make tail point to it if (this.tail.next != null) { this.tail = this.tail.next; } return node; }
請注意,我們已將位置指定為最後一個元素。這是因為,如果您不提供位置,則預設情況下它將插入到末尾。
您可以使用以下方法進行測試:
示例
let list = new LinkedList(); list.insert(10); list.insert(20); list.insert(30); list.insert(15, 2); list.display();
輸出
這將給出以下輸出:
10 <-> 30 <-> 15 <-> 20 <->
正如我們所看到的,所有元素都按我們預期的順序排列。我們嘗試在 2 之後的位置插入 15。
廣告