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)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Replace every node of a Linked list with the greatest element on right side
- Create new linked list from two given linked list with greater element at each node
- Replace nodes with duplicates in linked list
- Replace even nodes of a doubly linked list with the elements of array
- Swap Kth node from beginning with Kth node from end in a Doubly Linked List
- Swap Kth node from beginning with Kth node from end in a Linked List
- Remove last node of the linked list
- Remove first node of the linked list
- Squareroot(n)-th node in a Linked List
- Remove Nth node from end of the Linked List
- Delete Nth node from the end of the given linked list
- Remove every k-th node of the linked list
- Program for n'th node from the end of a Linked List
- Linked List | Set 2 (Inserting a node)
- Linked List | Set 3 (Deleting a node)
- Find the balanced node in a Linked List
- Delete a Linked List node at a given position
- Sum of nodes in a linked list which are greater than next node
- Find first node of loop in a linked list
- Reverse each word in a linked list node