Given a linked list. the task is to move all 0’s to the front of the linked list. The order of all other elements except 0 should be the same after rearrangement.
Input : 0 1 0 1 2 0 5 0 4 0 Output :0 0 0 0 0 1 1 2 5 4 Input :1 1 2 3 0 0 0 Output :0 0 0 1 1 2 3
A simple solution is to store all linked list element in an array. Then move all elements of the array to the beginning. Finally, copy array elements back to the linked list.
An efficient solution is to traverse the linked list from second node. For every node with 0 value, we disconnect it from its current position and move the node to front.
Linked list before rearrangement 0->0->1->0->1->0->2->0->3->0->NULL Linked list after rearrangement 0->0->0->0->0->0->1->1->2->3->NULL
- 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
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 Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.