Given a linked list and a value x, partition a linked list around a value x, such that all nodes less than x come before all nodes greater than or equal to x. If x is contained within the list the values of x only need to be after the elements less than x (see below). The partition element x can appear anywhere in the “right partition”; it does not need to appear between the left and right partitions.
Input : 3 -> 5 -> 10 -> 2 -> 8 -> 2 -> 1 x = 5 Output : 1-> 2-> 2-> 3-> 5-> 10-> 8
If we don’t care about making the elements of the list “stable” then we can instead rearrange the elements by growing the list at the head and tail.
In this approach, we start a “new” list (using the existing nodes). Elements bigger than the pivot element are put at the tail and elements smaller are put at the head. Each time we insert an element, we update either the head or tail.
Below is the implementation of above idea.
1 2 2 3 5 8 10
This article is contributed by Mr. Somesh Awasthi. 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