Remove Nodes From Linked List

You are given the head of a linked list. Remove every node that has a node with a strictly greater value anywhere to its right, and return the head of the modified list.

30:00

Remove Nodes From Linked List
medium
Free written solution
Topics
Companies

You are given the head of a linked list. Remove every node that has a node with a strictly greater value anywhere to its right, and return the head of the modified list.

Example 1:
Input: {"head":[5,2,13,3,8]}
Output: [13,8]
Constraints:
  • The number of nodes in the list is in the range [1,105][1, 10^5].

  • 1≤Node.val≤1051 \leq \text{Node.val} \leq 10^5

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"head":[5,2,13,3,8]}

Walk the list once, keeping a stack of survivors whose values never increase from bottom to top. A node survives only if nothing bigger comes after it.

▼ node: being processed■ on the stack (survivors so far)✕ popped: a bigger node came later
null521338

Stack, bottom to top (0)

empty

Variables
VariableValue
nodenull
stack[]
removed0
DepthFunction Call
Stack empty
0/23