Given LinkedList, replace each node’s value with its surpasser count. That is the count of elements which are greater towards its right.
Input : 10->12->5->40->21->70->1->49->37->NULL
Output : 6->5->5->2->3->0->2->0->0->NULL
Element in the first node is 10 and the number of elements to the right of the node that are greater than 10 is 6. Therefore replace the node with 6.
Element in the first node is 12 and the number of elements to the right of the node that are greater than 12 is 5. Therefore replace the node with 5.
Similarly, replace for all the elements in the list.
Input : 5->4->6->3->2->NULL
Output : 1->1->0->0->0->NULL
- Take two pointers p and x. The pointer p is used to traverse the list and x is used to traverse the right half of the list for every node.
- Initialize a variable count to count the nodes greater than the current nodes.
- Traverse through all the nodes in the list using the pointer p.
- Initialize the count to 0.
- Initialize the pointer x to point the current node p.
- Count the number of nodes that are greater than the current node.
- Replace the current node with the count.
- Repeat step 4 until the list is traversed completely.
Below is the implementation of the above approach:
6 5 5 2 3 0 2 0 0
Time Complexity: O(N2) where N is the number of nodes in the linked list.
Auxiliary Space: O(1)
- Create new linked list from two given linked list with greater element at each node
- Swap Kth node from beginning with Kth node from end in a Linked List
- Replace nodes with duplicates in linked list
- Replace even nodes of a doubly linked list with the elements of array
- Remove Nth node from end of the Linked List
- Squareroot(n)-th node in a Linked List
- Program for n'th node from the end of a Linked List
- Remove first node of the linked list
- Linked List | Set 2 (Inserting a node)
- Delete Nth node from the end of the given linked list
- Remove every k-th node of the linked list
- Linked List | Set 3 (Deleting a node)
- Remove last node of the linked list
- Delete every Kth node from circular linked list
- Insert node into the middle of the linked list
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.