我們將實現一個函數來刪除鏈表中右側具有更大值的節點。方法是從右向左遍歷鏈表并跟蹤到目前為止遇到的最大值。對于每個節點,我們將其值與最大值進行比較,如果其值小于最大值則刪除該節點。這樣,右側所有大于最大值的節點都會被刪除。
方法
刪除右側值較大的節點的方法可以分為以下 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 程序刪除右側具有更大值的節點的詳細內容,更多請關注www.92cms.cn其它相關文章!






