<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 removeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:



        h1=head
        s=[]
        while h1!=None:
            s.append(h1.val)
            h1=h1.next
        # i=0
        s=sorted(s)
        x = [0 for i in range(0, 10**5 + 1)]
        for num in s:
            x[num] += 1
        
        while head.val != s[-1]:
            x[head.val] -= 1
            head = head.next
            
        
        head1 = head
        h = head.next

        x[s[-1]] -= 1
        # print(x)
        
        if x[s[-1]] == 0:
            del s[-1]

        

        while h != None:
            if  x[s[-1]] > 0 and h.val != s[-1]:
                x[h.val] -= 1
                h = h.next
            elif x[s[-1]] == 0:
                del s[-1]
            else:
                head.next = h
                head = head.next
                h = h.next
                x[s[-1]] -= 1
                if x[s[-1]] == 0:
                    del s[-1]
        
        return head1

        # while head.val!=s[-1]:
        #     head=head.next
        #     del s[i]
        # del s[0]
        # h=head
        # while h.next!=None:
        #     if  h.next.val!=s[-1]:
        #         h.next=h.next.next
        #         del s[i]
        #     else:
        #         h=h.next
        #         del s[i]
        # return head



51956