Given a linked list with some two adjacent repeating nodes before a zero, task is to double the first and make next 0. After this, append all the zeros to tail.
Prerequisite: Basics of implementation of Singly Linked List
Input : 4 -> 4 -> 0 -> 2 -> 3 -> 4 -> 3 -> 3 -> 0 -> 4 -> Output : 8-> 2-> 3-> 4-> 6-> 4-> 0-> 0-> 0-> 0-> Explanation : First, after doubling the first element and making second element 0 before all zeros. 8 -> 0 -> 0 -> 2 -> 3 -> 4 -> 6 -> 0 -> 0 -> 4 -> Next : 8 -> 6 -> 5 -> 6 -> 0 -> 0 -> 0 -> 0 -> 0 -> 0 -> 0 -> Input : 0 -> 4 -> 4 -> 0 -> 3 -> 3 -> 0 -> 5 -> 0 -> 0 -> 6 -> Output : 8 -> 6 -> 5 -> 6 -> 0 -> 0 -> 0 -> 0 -> 0 -> 0 -> 0 ->
Traverse through the linked list, and wherever there are two adjacent same data of nodes before a 0 (e.g. 4 -> 4 -> 0), then, double first element and make another as 0 (e.g. 8 -> 0 -> 0 ->). Finally, traverse the linked list and linearly point all the zeros to tail.
Original linked list : 4 -> 4 -> 0 -> 2 -> 3 -> 4 -> 3 -> 3 -> 0 -> 4 -> Modified linked list : 8 -> 2 -> 3 -> 4 -> 6 -> 4 -> 0 -> 0 -> 0 -> 0 ->
Time complexity : O(n), where n is the number of nodes of linked list.
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.
- Append the last M nodes to the beginning of the given linked list
- Move all zeros to the front of the linked list
- Given a linked list, reverse alternate nodes and append at the end
- Delete multiple occurrences of key in Linked list using double pointer
- Append odd position nodes in reverse at the end of even positioned nodes in a Linked List
- Partitioning a linked list around a given value and If we don't care about making the elements of the list "stable"
- Reverse even elements in a Linked List
- Reverse first K elements of given linked list
- Find unique elements in linked list
- Sum of smaller elements of nodes in a linked list
- Move last m elements to the front of a given Linked List
- Pairwise swap elements of a given linked list
- Check if elements of Linked List are present in pair
- Insert N elements in a Linked List one after other at middle position
- Count minimum frequency elements in a linked list
- Find smallest and largest elements in singly linked list
- Sort the linked list in the order of elements appearing in the array
- Pairwise swap elements of a given linked list by changing links
- Replace even nodes of a doubly linked list with the elements of array
- Find minimum and maximum elements in singly Circular Linked List
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 Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.