

Can you solve this in linear time and constant space complexity?
The first line contains an integer 'T' which denotes the number of test cases or queries to be run. Then, the T test cases follow.
The first and only line of each test case contains space-separated integers denoting the values of nodes of the Linked List. The Linked List is terminated with -1. Hence, -1 is never a node value of the Linked List.
For more clarity please refer to the sample inputs.
For each test case, delete all the nodes which have a strictly greater value on the right side to this node.
Output for each test case will be printed in a separate line.
You do not need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 100
1 <= N <= 5000
1 <= node.data <= 10^9 (node.data != -1)
Time limit: 1 second
Traverse each node of the Linked List and for each node run a loop from that node to the end of the Linked List to check whether there exists a node having a value greater than the current node. If such a node exists, then we delete the current node, else we just move on to the next node.
Instead of finding a greater value for each node of the Linked List, we can find the suffix Max of the Linked List, and for each node, if the suffix Max is greater than the value of the current node, then we delete this node, else we keep it. For example, if the Linked List is 10 → 8 → 7 → 12 → 5. Then the suffixMax of all the elements should look like, [12, 12, 12, 12, 5]. So, as the value of the first three nodes is less than their respective suffix Max values, so we delete these three nodes. Since, unlike an array, we do not have direct access to all the nodes of the Linked List, in order to implement above the idea, we can just reverse the Linked List, store the prefix Max, and perform the above operations and then reverse the Linked List again.
Sorted Doubly Linked List to Balanced BST
Longest Substring with K-Repeating Characters
Expression Add Operators
Gray Code Transformation
Count of Subsequences with Given Sum