You are given a linked list of integers where each node has two fields: data field which contains a value, 'next' field which points to its adjacent node to the right or NULL if it is the last node. Your task is to delete all such nodes X, whose adjacent nodes to the right have strictly greater value than the value of X.
A singly linked list is a linear data structure in which we can traverse only in one direction i.e. from Head to Tail. It consists of several nodes where each node contains some data and a reference to the next node.
A sample Linked List-
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.
Output format:
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.
Note:
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
2
8 7 8 4 5 6 2 1 -1
6 5 3 2 1 -1
8 8 6 2 1 -1
6 5 3 2 1 -1
For the first test case, the given Linked List is

So, the 2nd, 4th and the 5th nodes have greater values on their right sides. Hence, we delete these nodes. So, after deleting these nodes the Linked List becomes 8 → 8 → 6 → 2 → 1, which is shown in the below figure.

For the second test case, the given Linked List is

Since there are no such nodes that have greater values on the right sides, the Linked List remains unchanged.
2
10 8 7 12 5 -1
5 6 7 8 10 12 -1
12 5 -1
12 -1
Think of a brute force solution to check whether there exists a greater node on the right side for each node.
Approach:
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.
Steps:
O(N ^ 2), where N is the total number of nodes in the Linked List.
Since for each node of the Linked List, we are traversing all the nodes starting from that node to the end of the Linked List. So, total N * (N + 1)/2 operations are being performed. Hence, the time complexity is O(N ^ 2).
O(1)
Constant space is used.