Given a linked list and a key in it, the task is to move all occurrences of given key to end of linked list, keeping order of all other elements same.
Input : 1 -> 2 -> 2 -> 4 -> 3 key = 2 Output : 1 -> 4 -> 3 -> 2 -> 2 Input : 6 -> 6 -> 7 -> 6 -> 3 -> 10 key = 6 Output : 7 -> 3 -> 10 -> 6 -> 6 -> 6
A simple solution is to one by one find all occurrences of given key in linked list. For every found occurrence, insert it at the end. We do it till all occurrences of given key are moved to end.
Time Complexity : O(n2)
Efficient Solution 1 : is to keep two pointers:
pCrawl => Pointer to traverse the whole list one by one.
pKey => Pointer to an occurrence of key if a key is found. Else same as pCrawl.
We start both of the above pointers from head of linked list. We move pKey only when pKey is not pointing to a key. We always move pCrawl. So when pCrawl and pKey are not same, we must have found a key which lies before pCrawl, so we swap data of pCrawl and pKey, and move pKey to next location. The loop invariant is, after swapping of data, all elements from pKey to pCrawl are keys.
Below is the C++ implementation of this approach.
Before moveToEnd(), the Linked list is 10 20 10 30 40 10 60 After moveToEnd(), the Linked list is 20 30 40 60 10 10 10
Time Complexity : O(n) requires only one traversal of list.
Efficient Solution 2 :
1. Traverse the linked list and take a pointer at tail.
2. Now, check for the key and node->data, if they are equal, move the node to last-next, else move
Thanks to Ravinder Kumar for suggesting this method.
Efficient Solution 3 : is to maintain a separate list of keys. We initialize this list of keys as empty. We traverse given list. For every key found, we remove it from the original list and insert into the separate list of keys. We finally link list of keys at the end of remaining given list. Time complexity of this solution is also O(n) and it also requires only one traversal of list.
This article is contributed by MAZHAR IMAM KHAN. 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.
- Remove all occurrences of duplicates from a sorted Linked List
- Search in an array of strings where non-empty strings are sorted
- Implementing Iterator pattern of a single Linked List
- Search, insert and delete in a sorted array
- Find all triplets with zero sum
- Count pairs in a binary tree whose sum is equal to a given value x
- Mu Sigma Interview On Campus
- Bank Of America (BA Continuum India Pvt. Ltd.) Campus Recruitment
- Bubble Sort On Doubly Linked List
- Reverse nodes of a linked list without affecting the special characters