/*
LinkedList1 : 7 -> 4 -> 6 -> 9 -> 3
LinkedList2 : 2 -> 5 -> 4
SumList : 7 -> 4 -> 9 -> 4 -> 7
LinkedList1 : 1 -> 2 -> 3 -> 4
LinkedList2 : 5 -> 4 -> 3 -> 2 -> 8
SumList : 5 -> 5 -> 5 -> 6 -> 2
LinkedList1 : 8 -> 7 -> 6 -> 5 -> 4
LinkedList2 : 4 -> 3 -> 2 -> 1 -> 0
SumList : 1 -> 3 -> 0 -> 8 -> 6 -> 4
*/
class linkedList
{
/*
* This function returns the difference in length of both the linkedLists.
* If length of linkedList1 is greater than length of linkedList2 then +ve difference in no. of elements returned.
* If length of linkedList1 is less tahn length of linkededList2 then -ve difference in no. of elements is returned.
* If both the linkedLists have equal no. of nodes then 0 is returned.
*/
public int getLengthDifference(node ptr1, node ptr2)
{
int lengthList = 0;
while(ptr1!=null)
{
ptr1=ptr1.getNext();
lengthList++;
}
while(ptr2 != null)
{
ptr2=ptr2.getNext();
lengthList--;
}
return lengthList;
}
/*
* This function requires "START" node of both the linkedLists.
* start refers to start node of linkedList which called this function (list1 in our case)
* startList2 gets start node of second linkedList.
* It returns new linkedList object which is sum of both the linked lists.
*/
public linkedList getSumOfLinkedLists(node startList2)
{
int diff = getLengthDifference(start, startList2);
linkedList sum = new linkedList();
if(addLinkedLists(start, startList2, diff,sum) == 1)
sum.insertAtFront(1);
return sum;
}
/*
* To overcome difference in lenths of linkedLists "integer n" is passed to this function.
* n = difference in length of LinkedList1 and LinkedList2.
* n > 0 => LinkedList1 > linkedList2 so only elements of linkedList1 should be incremented until n =0 ( n = n-1 ).
* n < 0 => LinkedList2 > LinkedList1 so only elements of linkedList2 should be incremented until n = 0 ( n = n+1 ).
* n =0 => Equal elements now both lists should be incremented.
*/
public int addLinkedLists(node ptr1, node ptr2, int n,linkedList sumList)
{
if(ptr1 != null && ptr2 != null)
{
int val = 0;
int sum = 0;
if(n > 0)
{
val = addLinkedLists(ptr1.getNext(), ptr2, n-1 , sumList);
sum = ptr1.getData() + val;
}
else if(n < 0)
{
val = addLinkedLists(ptr1, ptr2.getNext(), n+1 , sumList);
sum = ptr2.getData() + val;
}
else
{
val = addLinkedLists(ptr1.getNext(), ptr2.getNext(), n , sumList);
sum = ptr1.getData()+ptr2.getData()+val ;
}
sumList.insertAtFront(sum%10);
return sum/10;
}
return 0;
}
public static void main(String args[])
{
linkedList list1 = new linkedList();
linkedList list2 = new linkedList();
//Insert elements in list1 and list2.
System.out.println("\nLIST AFTER ADDITION");
linkedList l = list1.getSumOfLinkedLists(list2.getStart());
l.displayList();
}
}
No comments:
Post a Comment