JavaScript程式:刪除連結串列的交替節點


我們將編寫一個JavaScript程式來刪除連結串列的交替節點。我們將使用while迴圈遍歷連結串列,同時跟蹤當前節點和前一個節點。在迴圈的每次迭代中,我們將跳過當前節點並將前一個節點直接連結到下一個節點,有效地從列表中刪除當前節點。此過程將重複進行,直到所有交替節點都從連結串列中刪除。

方法

  • 從頭到尾遍歷連結串列。

  • 對於每個節點,儲存其下一個節點。

  • 刪除當前節點的下一個節點。

  • 更新當前節點的next引用,指向下下個節點。

  • 移動到下一個節點,現在是下下個節點。

  • 重複此過程,直到到達連結串列的末尾。

  • 最後,在刪除所有交替節點後,返回連結串列的頭節點。

示例

這是一個在JavaScript中刪除連結串列交替節點的完整示例:

// Linked List Node
class Node {
   constructor(data) {
      this.data = data;
      this.next = null;
   }
}

// Linked List class
class LinkedList {
   constructor() {
      this.head = null;
   }
   
   // Method to delete alternate nodes
   deleteAlternate() {
      let current = this.head;
      while (current !== null && current.next !== null) {
         current.next = current.next.next;
         current = current.next;
      }
   }
   
   // Method to print the linked list
   printList() {
      let current = this.head;
      while (current !== null) {
         console.log(current.data);
         current = current.next;
      }
   }
}
// create a linked list
let list = new LinkedList();
list.head = new Node(1);
list.head.next = new Node(2);
list.head.next.next = new Node(3);
list.head.next.next.next = new Node(4);
list.head.next.next.next.next = new Node(5);
console.log("Linked List before deleting alternate nodes: ");
list.printList();
list.deleteAlternate();
console.log("Linked List after deleting alternate nodes: ");
list.printList();

解釋

  • 我們首先建立一個**Node**類,表示連結串列中的每個節點,其中包含一個**data**欄位和一個**next**欄位,指向列表中的下一個節點。

  • 然後,我們建立一個**LinkedList**類,其中包含連結串列的頭節點和一個**printList**方法來列印連結串列。

  • **LinkedList**類的**deleteAlternate**方法用於刪除連結串列中的交替節點。該方法迭代連結串列並更新每個節點的**next**指標,使其指向連結串列中的下下個節點,從而有效地刪除交替節點。

  • 最後,我們建立一個連結串列並在刪除交替節點之前和之後列印它。

更新於:2023年3月13日

166 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.