Given a singly linked list, with some positive numbers (valid numbers) and zeros (invalid numbers). Convert the linked list in such a way that if next valid number is same as current number, double its value and replace the next number with 0. After the modification, rearrange the linked list such that all 0’s are shifted to the end.
Input : 2->2->0->4->0->8 Output : 4->4->8->0->0->0 Input : 0->2->2->2->0->6->6->0->0->8 Output : 4->2->12->8->0->0->0->0->0->0
Approach: First modify the linked list as mentioned, i.e., if next valid number is same as current number, double its value and replace the next number with 0.
Algorithm for Modification:
1. ptr = head 2. while (ptr && ptr->next) 3. if (ptr->data == 0) || (ptr->data != ptr->next->data) 4. ptr = ptr->next 5. else 6. ptr->data = 2 * ptr->data 7. ptr->next->data = 0 8. ptr = ptr->next->next
After modifying the list segregate the valid (non-zero) and invalid (zero) elements. It is same as Segregating Even and Odd nodes in a Linked list.
Original List: 2 2 0 4 0 8 Modified List: 4 4 8 0 0 0
Time Complexity: O(n).
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.
- How to write C functions that modify head pointer of a Linked List?
- Modify contents of Linked List
- Modify contents of Linked List - Recursive approach
- Rearrange a linked list such that all even and odd positioned nodes are together
- Rearrange a linked list in to alternate first and last element
- Rearrange a given linked list in-place.
- Rearrange a Linked List in Zig-Zag fashion
- Rearrange a given list such that it consists of alternating minimum maximum elements
- Rearrange a Linked List in Zig-Zag fashion | Set-2
- Rearrange Odd and Even values in Alternate Fashion in Ascending Order
- Partitioning a linked list around a given value and If we don't care about making the elements of the list "stable"
- Difference between Singly linked list and Doubly linked list
- XOR Linked List - A Memory Efficient Doubly Linked List | Set 1
- XOR Linked List – A Memory Efficient Doubly Linked List | Set 2
- Merge a linked list into another linked list at alternate positions
- Sublist Search (Search a linked list in another list)
- Length of longest palindrome list in a linked list using O(1) extra space
- Convert singly linked list into circular linked list
- Rotate the sub-list of a linked list from position M to N to the right by K places
- Create new linked list from two given linked list with greater element at each node
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.