首頁  >  文章  >  web前端  >  JavaScript 程式刪除右側具有更大值的節點

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

WBOY
WBOY轉載
2023-09-10 13:49:021151瀏覽

JavaScript 程序删除右侧具有更大值的节点

我們將實作一個函數來刪除鍊錶中右側具有更大值的節點。方法是從右向左遍歷鍊錶並追蹤到目前為止遇到的最大值。對於每個節點,我們將其值與最大值進行比較,如果其值小於最大值則刪除節點。這樣,右側所有大於最大值的節點都會被刪除。

方法

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

  • 從頭到尾遍歷鍊錶。

  • 追蹤目前節點、前一個節點以及迄今為止看到的最大值。

  • 如果目前節點的值小於目前看到的最大值,則透過更新前一個節點的 next 指標來刪除目前節點。

  • 將目前看到的最大值更新為目前節點的值。

  • 將目前節點移到下一個節點。

  • 重複步驟 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 引用以指向目前節點的下一個節點來刪除該節點。

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

  • 刪除節點後的鍊錶將只包含值為以下的節點:

以上是JavaScript 程式刪除右側具有更大值的節點的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除