<p>You are given the <code>head</code> of a linked list.</p>

<p>Remove every node which has a node with a greater value anywhere to the right side of it.</p>

<p>Return <em>the </em><code>head</code><em> of the modified linked list.</em></p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2022/10/02/drawio.png" style="width: 631px; height: 51px;" />
<pre>
<strong>Input:</strong> head = [5,2,13,3,8]
<strong>Output:</strong> [13,8]
<strong>Explanation:</strong> 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.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> head = [1,1,1,1]
<strong>Output:</strong> [1,1,1,1]
<strong>Explanation:</strong> Every node has value 1, so no nodes are removed.
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li>The number of the nodes in the given list is in the range <code>[1, 10<sup>5</sup>]</code>.</li>
	<li><code>1 &lt;= Node.val &lt;= 10<sup>5</sup></code></li>
</ul>

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reverse_list(self, head: ListNode) -> ListNode:
        prev = None
        curr = head
        while curr:
            next_node = curr.next
            curr.next = prev
            prev = curr
            curr = next_node
        return prev

    def removeNodes(self, head: ListNode) -> ListNode:
        if not head:
            return head

        # Step 1: Reverse the linked list
        reversed_head = self.reverse_list(head)
        
        # Step 2: Traverse the reversed list and use a stack to keep track of valid nodes
        stack = []
        curr = reversed_head
        
        while curr:
            # Only add to stack if the current node is greater than or equal to the top of the stack
            if not stack or curr.val >= stack[-1].val:
                stack.append(curr)
            curr = curr.next

        # Step 3: Rebuild the list from the stack and reverse it back to original order
        dummy = ListNode(0)
        curr = dummy
        
        # Pop elements from the stack to maintain the correct order
        while stack:
            node = stack.pop()
            curr.next = node
            curr = curr.next
        
        # Ensure the last node points to None
        curr.next = None

        return dummy.next
418