-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAdd two numbers represented by linked lists
155 lines (124 loc) · 3.42 KB
/
Add two numbers represented by linked lists
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
//Add two numbers represented by linked lists
import java.util.*;
class Node {
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}
class GfG{
static void printList(Node n){
while(n != null) {
System.out.print(n.data + " ");
n = n.next;
}
System.out.println();
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
while(T-- > 0) {
int n = sc.nextInt();
int val = sc.nextInt();
Node num1 = new Node(val);
Node tail = num1;
for(int i = 0; i < n - 1; i++) {
val = sc.nextInt();
tail.next = new Node(val);
tail = tail.next;
}
int m = sc.nextInt();
val = sc.nextInt();
Node num2 = new Node(val);
tail = num2;
for(int i = 0; i < m - 1; i++) {
val = sc.nextInt();
tail.next = new Node(val);
tail = tail.next;
}
Solution g = new Solution();
Node res = g.addTwoLists(num1, num2);
printList(res);
}
}
}
class Node {
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}
class Solution{
static Node reverse(Node head){
Node prev = null, curr = head, next = null;
while(curr != null) {
next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}
static Node addTwoLists(Node num1, Node num2){
Node temp = null;
while(num1 != null && num1.data == 0) {
temp = num1;
num1 = num1.next;
}
if(temp != null) {
temp.next = null;
}
while(num2 != null && num2.data == 0) {
temp = num2;
num2 = num2.next;
}
if(temp != null) {
temp.next = null;
}
if(num1 == null && num2 == null) {
return new Node(0);
}
if(num1 == null) {
return num2;
}
if(num2 == null) {
return num1;
}
num1 = reverse(num1);
num2 = reverse(num2);
Node head1 = num1, head2 = num2;
temp = new Node(1);
Node ans = temp;
int carry = 0;
while(head1 != null && head2 != null) {
int sum = head1.data + head2.data + carry;
carry = sum / 10;
temp.next = new Node(sum % 10);
temp = temp.next;
head1 = head1.next;
head2 = head2.next;
}
while(head1 != null) {
int sum = head1.data + carry;
carry = sum / 10;
temp.next = new Node(sum % 10);
temp = temp.next;
head1 = head1.next;
}
while(head2 != null) {
int sum = head2.data + carry;
carry = sum / 10;
temp.next = new Node(sum % 10);
temp = temp.next;
head2 = head2.next;
}
if(carry != 0) {
temp.next = new Node(carry);
}
return reverse(ans.next);
}
}