-
Notifications
You must be signed in to change notification settings - Fork 0
/
Add two numbers represented by linked lists.java
74 lines (63 loc) · 1.67 KB
/
Add two numbers represented by linked lists.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// Add two numbers represented by linked lists
/*
Given two numbers represented by two lists, write a function that returns sum list. The sum list is list representation of addition of two input numbers.
Suppose you have two linked list 5->4 ( 4 5 )and 5->4->3( 3 4 5) you have to return a resultant linked list 0->9->3 (3 9 0).
*/
/*The Node is defined as
class Node
{
int data;
Node next;
Node(int d) {data = d; next = null; }
Node(){}
}
*/
class Test
{
Node addTwoLists(Node first, Node second)
{
int carry =0;
int sum;
Node temp;
Node prev;
int modulo;
Add_LinkedList res = new Add_LinkedList();
while(first !=null || second != null){
int f,s;
if(first!=null)
f= first.data;
else
f=0;
if(second != null)
s= second.data;
else
s = 0;
sum = carry + f + s;
if (sum>=10)
carry = 1;
else
carry = 0;
modulo = sum % 10;
res.push(modulo);
if(first !=null)
first = first.next;
if(second !=null)
second = second.next;
}
if(carry>0)
res.push(carry);
return rev(res.head);
}
public static Node rev (Node node){
Node prev =null;
Node current = node;
Node next =current.next;
while(current != null){
next = current.next;
current.next = prev;
prev = current;
current = next;
}
return prev;
}
}