Update appNew update is available. Click here to update.
Last Updated: 5 Oct, 2020
Append Nodes
Moderate
Problem statement

You have been given an integer Linked List.

After every 'M' nodes, you have to take the sum of the next 'N' nodes and append that sum to the linked list. Do this till the end of the Linked List.

Note:
You just need to return the head of the new linked list.

In case the linked list ends after adding K nodes, where K is any positive integer less than 'N'.Append the sum of those K nodes at the end of the linked list.
Input Format:
The first line of input contains an integer 'T' representing the number of Test cases.
The next 2 * 'T' lines denote the T test cases. Each test case consists of two lines.

The first line of each test case contains the elements of the Linked list separated by space and the linked list is terminated by -1.

The second line of each test case contains two integers separated by a single space denoting 'N' and 'M' respectively, where in the linked list, after every 'M' nodes, take the sum of the next 'N' nodes and append that sum to the linked list.
Output Format:
For each test case, return the modified linked list with elements separated by space.
Note:
You do not need to print anything, it has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 10        
1 <= n <= 10^4
1 <= N <= 10^4
1 <= M <= 10^4
-10^5 <= VAL <= 10^5

Where 'n' denotes the length of the linked list and 'VAL' represents a node value of the linked list.

Time limit: 1 sec
Approaches

01Approach

Initially maintain two variables, β€˜COUNTM’ and β€˜COUNTN’ and Initialize them to β€˜0’, where β€˜COUNTM’ will keep track of iterating β€˜M’ nodes which are to be skipped and β€˜COUNTN’ will keep track of iterating β€˜N’ nodes whose sum needs to be calculated. Also, maintain a boolean variable β€˜TURNN’ representing which variable to count on, β€˜N’ or β€˜M’. If the β€˜TURNN’ variable is β€˜TRUE’ we would increment on β€˜COUNTN’ else β€˜COUNTM’. Set β€˜TURNN’  to false because initially, we would increment β€˜COUNTM’ as we need to skip the first β€˜M’ nodes of the linked list.

 

Create a helper function with the help of which we will be recursively traversing through the linked list and pass all the required variables to the helper function as displayed in the code. After β€˜M’ recursive calls, ’COUNTM’ would be equal to β€˜M’, thereby which we will set β€˜COUNTM’ to β€˜0’, β€˜TURNN’ to β€˜TRUE’, and start incrementing β€˜COUNTN’. If β€˜COUNTN’ reaches β€˜N’, append the sum of those β€˜N’ nodes to the linked list. The base condition of the recursive helper function would be when we encounter the node’s next is β€˜NULL’. Here if β€˜TURNN’ is β€˜FALSE’, we would simply return β€˜HEAD’, otherwise, we would append the temporary sum to the end of the linked list and then return the β€˜HEAD’.