Java Program For Adding Two Numbers Represented By Linked Lists- Set 2
Last Updated :
03 Apr, 2023
Given two numbers represented by two linked lists, write a function that returns the sum list. The sum list is linked list representation of the addition of two input numbers. It is not allowed to modify the lists. Also, not allowed to use explicit extra space (Hint: Use Recursion).
Example :
Input:
First List: 5->6->3
Second List: 8->4->2
Output:
Resultant list: 1->4->0->5
We have discussed a solution here which is for linked lists where a least significant digit is the first node of lists and the most significant digit is the last node. In this problem, the most significant node is the first node and the least significant digit is the last node and we are not allowed to modify the lists. Recursion is used here to calculate sum from right to left.
Following are the steps.
- Calculate sizes of given two linked lists.
- If sizes are same, then calculate sum using recursion. Hold all nodes in recursion call stack till the rightmost node, calculate the sum of rightmost nodes and forward carry to the left side.
- If size is not same, then follow below steps:
- Calculate difference of sizes of two linked lists. Let the difference be diff.
- Move diff nodes ahead in the bigger linked list. Now use step 2 to calculate the sum of the smaller list and right sub-list (of the same size) of a larger list. Also, store the carry of this sum.
- Calculate the sum of the carry (calculated in the previous step) with the remaining left sub-list of a larger list. Nodes of this sum are added at the beginning of the sum list obtained the previous step.
Below is a dry run of the above approach:
Below image is the implementation of the above approach.
Java
public class linkedlistATN
{
class node
{
int val;
node next;
public node( int val)
{
this .val = val;
}
}
void printlist(node head)
{
while (head != null )
{
System.out.print(
head.val + " " );
head = head.next;
}
}
node head1, head2, result;
int carry;
void push( int val, int list)
{
node newnode = new node(val);
if (list == 1 )
{
newnode.next = head1;
head1 = newnode;
}
else if (list == 2 )
{
newnode.next = head2;
head2 = newnode;
}
else
{
newnode.next = result;
result = newnode;
}
}
void addsamesize(node n, node m)
{
if (n == null )
return ;
addsamesize(n.next, m.next);
int sum = n.val + m.val + carry;
carry = sum / 10 ;
sum = sum % 10 ;
push(sum, 3 );
}
node cur;
void propogatecarry(node head1)
{
if (head1 != cur)
{
propogatecarry(head1.next);
int sum = carry + head1.val;
carry = sum / 10 ;
sum %= 10 ;
push(sum, 3 );
}
}
int getsize(node head)
{
int count = 0 ;
while (head != null )
{
count++;
head = head.next;
}
return count;
}
void addlists()
{
if (head1 == null )
{
result = head2;
return ;
}
if (head2 == null )
{
result = head1;
return ;
}
int size1 = getsize(head1);
int size2 = getsize(head2);
if (size1 == size2)
{
addsamesize(head1, head2);
}
else
{
if (size1 < size2)
{
node temp = head1;
head1 = head2;
head2 = temp;
}
int diff = Math.abs(size1 - size2);
node temp = head1;
while (diff-- >= 0 )
{
cur = temp;
temp = temp.next;
}
addsamesize(cur, head2);
propogatecarry(head1);
}
if (carry > 0 )
push(carry, 3 );
}
public static void main(String args[])
{
linkedlistATN list = new linkedlistATN();
list.head1 = null ;
list.head2 = null ;
list.result = null ;
list.carry = 0 ;
int arr1[] = { 9 , 9 , 9 };
int arr2[] = { 1 , 8 };
for ( int i = arr1.length - 1 ;
i >= 0 ; --i)
list.push(arr1[i], 1 );
for ( int i = arr2.length - 1 ;
i >= 0 ; --i)
list.push(arr2[i], 2 );
list.addlists();
list.printlist(list.result);
}
}
|
Output:
1 0 1 7
Time Complexity:
O(m+n) where m and n are the sizes of given two linked lists.
Auxiliary Space: O(n+m) due to recursive stack space
Iterative Approach: This implementation does not have any recursion call overhead, which means it is an iterative solution. Since we need to start adding numbers from the last of the two linked lists. So, here we will use the stack data structure to implement this.
- We will firstly make two stacks from the given two linked lists.
- Then, we will run a loop till both the stack become empty.
- in every iteration, we keep the track of the carry.
- In the end, if carry>0, that means we need an extra node at the start of the resultant list to accommodate this carry.
Java
import java.io.*;
import java.util.*;
class GFG{
static class Node
{
int data;
Node next;
public Node( int data)
{
this .data = data;
}
}
static Node l1, l2, result;
public static void push( int new_data)
{
Node new_node = new Node( 0 );
new_node.data = new_data;
new_node.next = l1;
l1 = new_node;
}
public static void push1( int new_data)
{
Node new_node = new Node( 0 );
new_node.data = new_data;
new_node.next = l2;
l2 = new_node;
}
public static Node addTwoNumbers()
{
Stack<Integer> stack1 =
new Stack<>();
Stack<Integer> stack2 =
new Stack<>();
while (l1 != null )
{
stack1.add(l1.data);
l1 = l1.next;
}
while (l2 != null )
{
stack2.add(l2.data);
l2 = l2.next;
}
int carry = 0 ;
Node result = null ;
while (!stack1.isEmpty() ||
!stack2.isEmpty())
{
int a = 0 , b = 0 ;
if (!stack1.isEmpty())
{
a = stack1.pop();
}
if (!stack2.isEmpty())
{
b = stack2.pop();
}
int total = a + b + carry;
Node temp = new Node(total % 10 );
carry = total / 10 ;
if (result == null )
{
result = temp;
}
else
{
temp.next = result;
result = temp;
}
}
if (carry != 0 )
{
Node temp = new Node(carry);
temp.next = result;
result = temp;
}
return result;
}
public static void printList()
{
while (result != null )
{
System.out.print(result.data +
" " );
result = result.next;
}
System.out.println();
}
public static void main(String[] args)
{
int arr1[] = { 5 , 6 , 7 };
int arr2[] = { 1 , 8 };
int size1 = 3 ;
int size2 = 2 ;
int i;
for (i = size1 - 1 ;
i >= 0 ; --i)
push(arr1[i]);
for (i = size2 - 1 ;
i >= 0 ; --i)
push1(arr2[i]);
result = addTwoNumbers();
printList();
}
}
|
Output:
5 8 5
Time Complexity: O(m + n) where m and n are the number of nodes in the given two linked lists.
Auxiliary Space: O(m+n), where m and n are the number of nodes in the given two linked lists.
Related Article: Add two numbers represented by linked lists | Set 1 Please refer complete article on Add two numbers represented by linked lists | Set 2 for more details!
Share your thoughts in the comments
Please Login to comment...