Sunday, 13 August 2017

Write a program in java to do addition between two Linked List

This is one of the most common and tricky question in JAVA interview. I have faced this question during my interview with Nokia R&D.

We have two Linked Lists L1 and L2 having same or different size. We need to print the output.

Sample example1,
LinkedList l1: 4-->5-->3

LinkedList l2: 4-->5-->2

Output should be:
LinkedList l3: 8-->0-->6

Sample example2:

LinkedList l1: 4-->5-->3-->6

LinkedList l2: 4-->5-->2

Output:

LinkedList l3: 8-->0-->6-->6

Sample Code:

public class LinkListAddition {
public static void main(String[] args) {
LinkedList<Integer> linkList1=new LinkedList<>();
LinkedList<Integer> linkedList2=new LinkedList<>();
linkList1.add(2);/* adding values into the link lists*/ 
linkList1.add(4);
linkList1.add(3);
linkedList2.add(5);
linkedList2.add(6);
linkedList2.add(4);
linkedList2.add(8);
int carry=0;
Iterator<Integer> it1=linkList1.iterator();
Iterator<Integer> it2=linkedList2.iterator();
LinkedList< Integer> finalList=new LinkedList<>();
// Iterate through LinkedList 
while(it1.hasNext() || it2.hasNext())
{
int i=0;
int x=(it1.hasNext()?it1.next():0);
int y=(it2.hasNext()?it2.next():0);
int sum=x+y+carry;
if(sum>=10)
{
carry=sum/10;
finalList.add(sum%10);
}
else
{
finalList.add(sum%10);
carry=0;
}
i=i+1;
}
System.out.println("Lined List1: "+linkList1+" Linked List 2: "+ linkedList2 );
System.out.println("Output below:");
Iterator<Integer> it3=finalList.iterator();
while(it3.hasNext())
{
System.out.println("=>"+it3.next());
}
}
}


Sample Output:

Lined List1: [2, 4, 3] Linked List 2: [5, 6, 4, 8]
Output below:
=>7
=>0
=>8
=>8


No comments:

Post a Comment

Use of Lamda Expression and Functional Interface in JAVA 8

In this blog, we are going to discuss one of the most important features of JAVA 8 which is Lamda Expression and Functional Interface. A...