Given a linked list containing a series of numbers that are separated by ‘0’. You need to find the sum of the series and replace the series’s elements with its sum.
For Example :If the given linked list is 3 ->4 ->0 ->5 ->0, you should return linked list as - 7 -> 5.
Note :
You need to replace the sum values in the linked list without using any extra space.
It is guaranteed that there will be no two consecutive zeroes in the linked list.
The first line of input contains an integer ‘T’ denoting the number of test cases.
The first line of each test case contains integers denoting the nodes of the linked list. Each line is guaranteed to have -1 at the end to signify the end of the linked list. Also, None of the elements of the linked list is -1.
Output Format :
For each test case, print space-separated integers denoting the nodes of the output linked list, in a separate line.
Each new line denotes a separated linked list.
Note :
You don't need to print anything, it has already been taken care of. Just implement the given function.
1 <= T <= 50
1 <= N <= 10^5
-10^9 <= data <= 10^9
data ≠ -1.
Time Limit: 1 sec
2
2 5 7 0 3 4 0 -1
1 2 3 0 -1
14 7
6
Test Case 1: In the given linked list sum of series 2, 5, 7 is 14, and the sum of series 3,4 is 7. So the modified, linked list will be 14 -> 7.
Test Case 2: The only series formed in the linked list 1,2,3 have sum = 6. Therefore modified linked list will be 6.
2
5 3 8 2 -1
0 6 0 4 0 -1
5 3 8 2
6 4
Think of traversing the linked list.
The simple idea is to traverse the linked list and store the sum of nodes in a variable ‘sum’ until ‘0’ is not encountered. We will store this ‘sum’ value in every series’s first node and link all these nodes containing sum values.
Algorithm:
Let us understand the above approach with an example.
O( N ), where ‘ N ‘ is the number of nodes in the linked list.
We are traversing through the linked list once. So the time complexity is O( N ).
O( 1 )
We have not used any extra space. So the space complexity is constant.