Sponsored
Sponsored
This approach involves reversing the linked list and using a stack to maintain the maximum values encountered so far. This allows us to easily determine which nodes have a greater value to their right.
Time Complexity: O(n), where n is the number of nodes in the linked list since each node is processed twice.
Space Complexity: O(n), due to the use of an additional stack to store nodes.
1class ListNode:
2 def __init__(self, val=0, next=None):
3 self.val = val
4 self.next = next
5
6class Solution:
7 def removeNodes(self, head: ListNode) -> ListNode:
8 stack = []
9 current = head
10
11 # Traverse the list in a reversed manner
12 while current:
13 while stack and stack[-1].val <= current.val:
14 stack.pop()
15 stack.append(current)
16 current = current.next
17
18 # Reconstruct the result list from the stack
19 dummy = ListNode(0)
20 last = dummy
21 for node in reversed(stack):
22 last.next = ListNode(node.val)
23 last = last.next
24 return dummy.next
The code defines a function removeNodes
that takes a singly linked list and removes nodes that have a node with a greater value to their right. It uses a stack to keep track of potential candidates for the resulting list, reconstructing the list after determining the correct elements.
This approach uses recursion to traverse the list and solve the problem recursively by backtracking from the end of the list to the start.
Time Complexity: O(n) - as each node is visited exactly once.
Space Complexity: O(n) - due to recursive stack space used during function calls.
1function ListNode(val, next) {
2 this
The JavaScript implementation employs recursion to traverse the linked list and decide post-traversal which nodes should be retained by safely backtracking to the start, verifying each node’s validity.