JavaScript程式:刪除右側值更大的節點


我們將實現一個函式,用於刪除連結串列中右側值更大的節點。方法是從右到左遍歷連結串列,並跟蹤迄今為止遇到的最大值。對於每個節點,我們將它的值與最大值進行比較,如果它的值小於最大值,則刪除該節點。這樣,所有右側值大於其自身值的節點都將被刪除。

方法

刪除右側值更大的節點的方法可以解釋為以下7個步驟:

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

  • 跟蹤當前節點、前一個節點和迄今為止看到過的最大值。

  • 如果當前節點的值小於迄今為止看到過的最大值,則透過更新前一個節點的下一個指標來刪除當前節點。

  • 將迄今為止看到過的最大值更新為當前節點的值。

  • 將當前節點移動到下一個節點。

  • 重複步驟3到5,直到到達連結串列的末尾。

  • 返回更新後的連結串列的頭節點。

示例

給定一個單鏈表,任務是刪除右側值更大的節點。其思想是從右到左遍歷列表,並跟蹤迄今為止看到過的最大值。當我們遍歷列表時,我們刪除其值小於迄今為止看到過的最大值節點。

以下是JavaScript中的實現:

class Node {
  constructor(value) {
    this.value = value;
    this.next = null;
  }
}
class LinkedList {
  constructor() {
    this.head = null;
  }
  // Add a new node to the linked list
  add(value) {
    const node = new Node(value);
    if (!this.head) {
      this.head = node;
      return;
    }
    let current = this.head;
    while (current.next) {
      current = current.next;
    }
    current.next = node;
  }
  // Function to delete nodes with greater value on right
  deleteNodes() {
    let prev = null;
    let current = this.head;
    let max = this.head.value;
    // Traverse the linked list from right to left
    while (current.next) {
      // If the current node has a greater value than the max value seen so far
      if (current.next.value > max) {
        max = current.next.value;
        prev = current;
      } else {
        // Delete the node with smaller value
        prev.next = current.next;
      }
      current = current.next;
    }
    // If the last node has a smaller value than the max value seen so far
    if (this.head.value < max) {
      this.head = this.head.next;
    }
  }
}
// Test the code
const linkedList = new LinkedList();
linkedList.add(12);
linkedList.add(15);
linkedList.add(10);
linkedList.add(11);
linkedList.add(5);
linkedList.add(6);
linkedList.add(2);
linkedList.add(3);
linkedList.deleteNodes();
let current = linkedList.head;
while (current) {
  console.log(current.value);
  current = current.next;
}

解釋

  • 首先,我們建立一個連結串列類和一個Node類來定義列表中的每個節點。

  • 在LinkedList類中,我們有一個add()函式用於向列表中新增新節點。

  • deleteNodes()函式實現了刪除右側值更大的節點的邏輯。

  • 我們從右到左遍歷列表,跟蹤迄今為止看到過的最大值。

  • 如果當前節點的值大於最大值,則更新最大值。

  • 如果當前節點的值小於最大值,則透過更新前一個節點的next引用指向當前節點的下一個節點來刪除該節點。

  • 最後,如果第一個節點的值小於最大值,則更新頭引用以指向第一個節點的下一個節點。

  • 刪除節點後,連結串列將只包含值……的節點

更新於:2023年3月13日

235 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告