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 firstname.lastname@example.org. 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.
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.
- Partitioning a linked list around a given value and keeping the original order
- Create new linked list from two given linked list with greater element at each node
- XOR Linked List – A Memory Efficient Doubly Linked List | Set 2
- Merge a linked list into another linked list at alternate positions
- Convert singly linked list into circular linked list
- XOR Linked List - A Memory Efficient Doubly Linked List | Set 1
- Difference between Singly linked list and Doubly linked list
- Reverse first K elements of given linked list
- Reverse even elements in a Linked List
- Move last m elements to the front of a given Linked List
- Find unique elements in linked list
- Sum of smaller elements of nodes in a linked list
- Pairwise swap elements of a given linked list
- Double elements and append zeros in linked list
- Insert N elements in a Linked List one after other at middle position
- Count minimum frequency elements in a linked list
- Check if elements of Linked List are present in pair
- Length of longest palindrome list in a linked list using O(1) extra space
- Pairwise swap elements of a given linked list by changing links
- Replace even nodes of a doubly linked list with the elements of array