
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.
Given a Linked List: 1-2-3-4-5-5-6
First half: 1-2-3-4
Reversed second half: 6-5-5
Output linkedlist: 1-8-8-9 = (1234 + 655 = 1889)
Can you add both halves without finding the length of LinkedList 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.
For each input, print a single line containing a string denoting the required sum.
You do not need to print anything; it has already been taken care of. Just implement the given function.
0 <= 'N' <= 10 ^ 5
0 <= 'DATA' <= 9
Where 'N' is the number of nodes in linked list and 'DATA' is the integer value in each node.
Time Limit: 1 sec
In this approach, we will first iterate through the LinkedList and find the length of the given linked list. Then we will initialize two LinkedList ‘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 only the first list(the second list already contains the least significant digit at its head) so that the head node contains the least significant digit of the first number.
Now the task remaining is to add two numbers represented by two linked lists 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.
In this approach, instead of finding the length of linkedlist in one traversal, we will use two pointers ‘slow’ and ‘fast’ to traverse the list. The slow pointer will point to the next node and the fast pointer will skip one node and will points to the next of the next node after one iteration.
Now we will do changes in the given linked list and store the two heads ‘head1’ and ‘head2’ for both halves. While traversing the given list reverse it until the fast pointer become null. In this way, we will have our first half with head ‘head1’ and the least significant digit in the head itself. Now the slow pointer will point to the least significant digit of the reversed second half. So just use it as the head2(head of the reversed second list).
Now we will add both the lists and store the results in one of the lists itself in the reversed order and return the head.