


You are given a Singly Linked List of N nodes such that each node represents a single digit.
Your task is to return a node 'X', where 'X' represents the head of the Linked List storing the digits of the sum(most significant digit at the head) formed by adding the 1st half and 2nd half of the given Linked List.
Note:
1. When N is odd consider the middle element to be part of 1st half.
2. The sum should not contain any leading zero, except the number 0 itself.
For Example:
Given Linked List: 1-2-3-4-5-5-6
First half: 1-2-3-4
Second half: 5-5-6
Output Linked List: 1-7-9-0 = (1234 + 556 = 1790)
Follow Up:
Can you add both halves without finding the length of Linked List and in O(1) space?
A single line of input contains the elements of the Singly Linked List separated by a single space and terminated by -1.
Output format :
Print a single line containing a string that denotes the required sum.
Note:
You are not required to print the output, it has already been taken care of. Just implement the function.
0 <= N <= 10^5
0 <= DATA <= 9
Where 'DATA' is the integer corresponding to the value of nodes of the given Linked List.
Time Limit: 1 sec
1 2 4 5 6 -1
180
The first half of the given Linked List is 1-2-4.
The second half of the given Linked List is 5-6.
Sum of both parts = 124 + 56 = 180.
3 9 0 1 1 0 -1
500
Find the length of linkedlist and divide it into two parts.
In this approach, we will first iterate through the Linked List and find the length of the given Linked List. Then we will initialize two Linked List ‘HEAD1’ and ‘HEAD2’ to store the two numbers.
We will iterate on the Linked List till half-length and create a new list to store the first half with a head equal to ‘HEAD1’. Similarly, we will keep the second half in a new list with a head equals to ‘HEAD2’. Now reverse both the lists so that their head nodes contain the least significant digits of both numbers.
Now the task remain is to add two numbers represented by two Linked List where the head of each denotes the least significant digit of two numbers. So to add them we will iterate on both simultaneously and keep on adding the corresponding digits with a flag for ‘CARRY’ and store the sum in a new list. This list will have the required sum with its least significant digit in the head. Now reverse the resultant list and return its head.
O(N), where N is the total number of nodes in the given Linked List.
Since we are iterating on the list twice. So the total time complexity is O(N).
O(N), where N is the total number of nodes in the given Linked List.
Since extra space is required to maintain the 3 new Linked Lists(2 for both halves and 1 for the resultant sum list) and so, the total space complexity is O(N).