graph LR;
A[5] --> B[2] --> C[13] --> D[3] --> E[8];
style C fill:#32CD32;
style E fill:#32CD32;
1
2
3
4
5
6
Input: head =[5,2,13,3,8]Output: [13,8]Explanation: The nodes that should be removed are 5,2 and 3.- Node 13is to the right of node 5.- Node 13is to the right of node 2.- Node 8is to the right of node 3.
Example 2:
1
2
3
Input: head =[1,1,1,1]Output: [1,1,1,1]Explanation: Every node has value 1, so no nodes are removed.
Reverse Traversal: To solve this problem, we can leverage the reverse traversal of the linked list. By traversing the list from the end to the beginning, we can keep track of the maximum value encountered so far and remove nodes that are smaller than this maximum.
Reversing the List: Firstly, reverse the linked list. This allows us to easily track the maximum value encountered in a single traversal.
Filtering Nodes: Traverse the reversed linked list, keeping the maximum value encountered and removing nodes smaller than this maximum value.
Reverse the List Back: Finally, reverse the list again to restore the original order with the nodes removed as required.