Remove Nodes From Linked List

You are given the head of a linked list.

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

Return the head of the modified linked list.

Example 1
[5] -> [2] -> [13] -> [3] -> [8] -> null
---
[13] -> [8] -> null
Inputhead = [5,2,13,3,8]
Output[13,8]
The nodes that should be removed are 5, 2 and 3 because 13 is to the right of 5 and 2, and 8 is to the right of 3.
Example 2
[1] -> [1] -> [1] -> [1] -> null
---
[1] -> [1] -> [1] -> [1] -> null
Inputhead = [1,1,1,1]
Output[1,1,1,1]
Every node has value 1, so no nodes are removed.

Constraints

  • The number of the nodes in the given list is in the range [1, 10^5].
  • 1 <= Node.val <= 10^5

Asked at 4 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate