Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit e3d25e3

Browse files
author
Ram swaroop
committed
add two no.s represented by lists: done
1 parent 296eff2 commit e3d25e3

File tree

1 file changed

+79
-0
lines changed

1 file changed

+79
-0
lines changed
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
package me.ramswaroop.linkedlists;
2+
3+
import me.ramswaroop.common.SingleLinkedList;
4+
import me.ramswaroop.common.SingleLinkedNode;
5+
6+
/**
7+
* Created by IntelliJ IDEA.
8+
*
9+
* @author: ramswaroop
10+
* @date: 7/2/15
11+
* @time: 1:20 PM
12+
*/
13+
public class AddNumbersInTwoLists {
14+
15+
/**
16+
* Adds two numbers represented by two linked lists {@param list1}
17+
* and {@param list2} and stores them in another list.
18+
* <p/>
19+
* Example:
20+
* <p/>
21+
* Input:
22+
* First List: 5->6->3 // represents number 365
23+
* Second List: 8->4->2 // represents number 248
24+
* Output:
25+
* Resultant list: 3->1->6 // represents number 613
26+
* <p/>
27+
* Input:
28+
* First List: 7->5->9->4->6 // represents number 64957
29+
* Second List: 8->4 // represents number 48
30+
* Output:
31+
* Resultant list: 5->0->0->5->6 // represents number 65005
32+
*
33+
* @param list1
34+
* @param list2
35+
* @return list containing the sum of numbers in {@param list1} and {@param list2}.
36+
*/
37+
public static SingleLinkedList<Integer> add(SingleLinkedList<Integer> list1,
38+
SingleLinkedList<Integer> list2) {
39+
40+
int sum, carry = 0;
41+
SingleLinkedNode<Integer> curr1 = list1.head, curr2 = list2.head;
42+
SingleLinkedList<Integer> resultList = new SingleLinkedList<>();
43+
44+
// loop till both of the list runs out
45+
while (curr1 != null || curr2 != null) {
46+
47+
// if either of the list runs out first
48+
int a = (curr1 != null) ? curr1.item : 0;
49+
int b = (curr2 != null) ? curr2.item : 0;
50+
51+
sum = (a + b + carry) % 10;
52+
carry = (a + b + carry) / 10;
53+
resultList.add(sum);
54+
55+
if (curr1 != null) curr1 = curr1.next;
56+
if (curr2 != null) curr2 = curr2.next;
57+
}
58+
59+
// if there is any carry left over, add it to the result
60+
if (carry != 0) resultList.addFirst(carry);
61+
62+
return resultList;
63+
}
64+
65+
public static void main(String a[]) {
66+
SingleLinkedList<Integer> linkedList1 = new SingleLinkedList<>();
67+
linkedList1.add(7);
68+
linkedList1.add(5);
69+
linkedList1.add(9);
70+
linkedList1.add(4);
71+
linkedList1.add(6);
72+
linkedList1.printList();
73+
SingleLinkedList<Integer> linkedList2 = new SingleLinkedList<>();
74+
linkedList2.add(8);
75+
linkedList2.add(4);
76+
linkedList2.printList();
77+
add(linkedList1, linkedList2).printList();
78+
}
79+
}

0 commit comments

Comments
 (0)