Given head of a linked list of integers and an integer k, your task is to modify the linked list as follows:
- Consider nodes in groups of size k. In every group, replace value of first node with group sum.
- Also, delete the elements of group except the first node.
- During traversal, if the remaining nodes in linked list are less than k then also do the above considering remaining nodes.
Input: N = 6, K = 2
Output: 3 7 11
We have denoted grouping of k elements by (). The elements inside () are summed.
1 -> 2 -> 3 -> 4 -> 5 -> 6 -> null
(1 -> 2) -> 3 -> 4 -> 5 -> 6 -> null
(3) -> 3 -> 4 -> 5 -> 6 -> null
3 -> (3 -> 4) -> 5 -> 6 -> null
3 -> (7) -> 5 -> 6 -> null
3 -> 7 -> (5 -> 6) -> null
3 -> 7 -> (11) -> null
3 -> 7 -> 11 -> null
Approach: Insert the given nodes in the Linked list. The approach of insertion has been discussed in this post. Once the nodes are inserted, iterate from the beginning of the list. Mark the first node as temp node. Iterate for the next k-1 nodes and sum up the nodes in sum variable. If the number of nodes is less than K, then replace the temp node’s data with sum and point temp to NULL. If there is a group with K nodes, replace the temp’s data with sum and move temp to the node which is just after K nodes. Continue the above operation till temp points to NULL. Once temp reaches the end, it means all groups of size K has been traversed and the node has been replaced with the sum of nodes of size K. Once the operation of replacements have been done, the linked list thus formed can be printed. The method of printing the linked list has been discussed in this post.
Below is the implementation of the above approach:
3 7 11
- Sudo Placement[1.5] | Partition
- Sudo Placement[1.5] | Wolfish
- Sudo Placement[1.4] | BST Traversal
- Sudo Placement[1.3] | Stack Design
- Sudo Placement[1.3] | Final Destination
- Sudo Placement[1.3] | Playing with Stacks
- Sudo Placement 2 | Matrix Series
- Sudo Placement | Beautiful Pairs
- Sudo Placement[1.5] | Second Smallest in Range
- Sudo Placement[1.4] | Jumping the Subtree
- Sudo Placement | Range Queries
- Sudo Placement | Palindrome Family
- Sudo Placement | Special Subsequences
- Sudo Placement[1.7] | Greatest Digital Root
- Sudo Placement | Placement Tour
This article is contributed by Team Geeksforgeeks. 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.
Improved By : princiraj1992