Given a linked list and a value x, partition it such that all nodes less than x come first, then all nodes with value equal to x and finally nodes with value greater than or equal to x. The original relative order of the nodes in each of the three partitions should be preserved. The partition must work in-place.
Input : 1->4->3->2->5->2->3, x = 3 Output: 1->2->2->3->3->4->5 Input : 1->4->2->10 x = 3 Output: 1->2->4->10 Input : 10->4->20->10->3 x = 3 Output: 3->10->4->20->10
To solve this problem we can use partition method of Quick Sort but this would not preserve the original relative order of the nodes in each of the two partitions.
Below is the algorithm to solve this problem :
- Initialize first and last nodes of below three linked lists as NULL.
- Linked list of values smaller than x.
- Linked list of values equal to x.
- Linked list of values greater than x.
- Now iterate through the original linked list. If a node’s value is less than x then append it at the end of smaller list. If the value is equal to x, then at the end of equal list. And if value is greater, then at the end of greater list.
- Now concatenate three lists.
Below is the implementation of above idea.
2 10 4 5 30 50
This article is contributed by Shashank Mishra ( Gullu ). 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 write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Find the middle of a given linked list in C and Java
- Program for n'th node from the end of a Linked List
- Write a function to get Nth node in a Linked List
- Given only a pointer/reference to a node to be deleted in a singly linked list, how do you delete it?
- Detect loop in a linked list
- Write a function to delete a Linked List
- Write a function that counts the number of times a given int occurs in a Linked List
- Reverse a linked list
- Given only a pointer to a node to be deleted in a singly linked list, how do you delete it?
- Write a function to get the intersection point of two Linked Lists
- Function to check if a singly linked list is palindrome
- The Great Tree-List Recursion Problem.
- Clone a linked list with next and random pointer | Set 1
- Memory efficient doubly linked list
- Given a linked list which is sorted, how will you insert in sorted way