我們將實(shí)現(xiàn)一個(gè)函數(shù)來刪除鏈表中右側(cè)具有更大值的節(jié)點(diǎn)。方法是從右向左遍歷鏈表并跟蹤到目前為止遇到的最大值。對于每個(gè)節(jié)點(diǎn),我們將其值與最大值進(jìn)行比較,如果其值小于最大值則刪除該節(jié)點(diǎn)。這樣,右側(cè)所有大于最大值的節(jié)點(diǎn)都會被刪除。
方法
刪除右側(cè)值較大的節(jié)點(diǎn)的方法可以分為以下 7 個(gè)步驟:
從頭到尾遍歷鏈表。
跟蹤當(dāng)前節(jié)點(diǎn)、前一個(gè)節(jié)點(diǎn)以及迄今為止看到的最大值。
如果當(dāng)前節(jié)點(diǎn)的值小于目前看到的最大值,則通過更新前一個(gè)節(jié)點(diǎn)的 next 指針來刪除當(dāng)前節(jié)點(diǎn)。
將目前看到的最大值更新為當(dāng)前節(jié)點(diǎn)的值。
將當(dāng)前節(jié)點(diǎn)移動到下一個(gè)節(jié)點(diǎn)。
重復(fù)步驟 3 到 5,直到到達(dá)鏈表末尾。
返回更新后的鏈表的頭。
示例
給定一個(gè)單鏈表,任務(wù)是刪除右側(cè)具有更大值的節(jié)點(diǎn)。這個(gè)想法是從右到左遍歷列表并跟蹤到目前為止看到的最大值。當(dāng)我們遍歷列表時(shí),我們刪除值小于目前看到的最大值的節(jié)點(diǎn)。
這是 JavaScript 中的實(shí)現(xiàn) –
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; }
登錄后復(fù)制
說明
首先,我們創(chuàng)建一個(gè)鏈表類,其中包含 Node 類來定義鏈表中的每個(gè)節(jié)點(diǎn)。
在 LinkedList 類中,我們有一個(gè)函數(shù) add() 來將新節(jié)點(diǎn)添加到列表中。
deleteNodes()函數(shù)實(shí)現(xiàn)刪除右側(cè)值較大的節(jié)點(diǎn)的邏輯。
我們從右向左遍歷列表,跟蹤到目前為止看到的最大值。
如果當(dāng)前節(jié)點(diǎn)的值大于最大值,我們更新最大值。
如果當(dāng)前節(jié)點(diǎn)的值小于最大值,我們通過更新前一個(gè)節(jié)點(diǎn)的 next 引用以指向當(dāng)前節(jié)點(diǎn)的下一個(gè)節(jié)點(diǎn)來刪除該節(jié)點(diǎn)。
最后,如果第一個(gè)節(jié)點(diǎn)的值小于最大值,我們更新頭引用以指向第一個(gè)節(jié)點(diǎn)的下一個(gè)節(jié)點(diǎn)。
刪除節(jié)點(diǎn)后的鏈表將只包含值為以下的節(jié)點(diǎn):
以上就是JavaScript 程序刪除右側(cè)具有更大值的節(jié)點(diǎn)的詳細(xì)內(nèi)容,更多請關(guān)注www.92cms.cn其它相關(guān)文章!