You are given the <code>head</code> of a linked list.Remove every node which has a node with a <strong>greater</strong> value anywhere to the <strong>right</strong> side of it.Return <em>the head of the modified linked list</em>.
Input: head = [5,2,13,3,8]Output: [13,8]Explanation: The nodes that should be removed are 5, 2 and 3.- Node 13 is to the right of node 5.- Node 13 is to the right of node 2.- Node 8 is to the right of node 3.
Input: head = [1,1,1,1]Output: [1,1,1,1]Explanation: Every node has value 1, so no nodes are removed.
from leetcode_py import ListNodeclass Solution: # Time: O(n) # Space: O(1) def remove_nodes(self, head: ListNode[int] | None) -> ListNode[int] | None: # Reverse the list so that "greater to the right" becomes "greater already kept". prev: ListNode[int] | None = None node = head while node is not None: nxt = node.next node.next = prev prev = node node = nxt cur = prev while cur is not None: nxt = cur.next if nxt is None: break if nxt.val < cur.val: cur.next = nxt.next else: cur = nxt # Reverse back to restore left-to-right order. result: ListNode[int] | None = None node = prev while node is not None: nxt = node.next node.next = result result = node node = nxt return result