Reverse the linked list to simplify the problem. This way, we can easily remove nodes that have a greater node on their right by comparing nodes during traversal.
Traverse and Track the Maximum Node:
Traverse the reversed list and keep track of the maximum value node encountered so far. Delete nodes that have a lower value compared to the maximum node.
Reverse the List Again:
Finally, reverse the list again to restore the original order, but with the desired nodes removed.
classSolution:
defdeleteNodesWithGreaterRight(self, head: ListNode) -> ListNode:
ifnot head:
returnNone# Step 1: Reverse the linked list reversed_head = self.reverseList(head)
# Step 2: Traverse and delete nodes with greater nodes on the right max_node = reversed_head
current = reversed_head
prev = reversed_head
while current and current.next:
if current.next.val < max_node.val:
# Delete the node current.next = current.next.next
else:
current = current.next
max_node = current
# Step 3: Reverse the list againreturn self.reverseList(reversed_head)
defreverseList(self, head):
prev, current =None, head
while current:
next_node = current.next
current.next = prev
prev = current
current = next_node
return prev