-
Notifications
You must be signed in to change notification settings - Fork 1
/
AddTwoNumbersRepresentedByLinkedLists.java
56 lines (49 loc) · 1.38 KB
/
AddTwoNumbersRepresentedByLinkedLists.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
/* node for linked list
class Node {
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}
*/
class Solution {
static Node addTwoLists(Node first, Node second) {
first = reverseList(first);
second = reverseList(second);
Node dummy = new Node(-1);
Node temp = dummy;
int carry = 0;
while (first != null || second != null || carry == 1) {
int sum = 0;
if (first != null) {
sum += first.data;
first = first.next;
}
if (second != null) {
sum += second.data;
second = second.next;
}
sum += carry;
carry = sum/10;
Node newnode = new Node(sum%10);
temp.next = newnode;
temp = temp.next;
}
Node ans = reverseList(dummy.next);
while(ans!=null && ans.data == 0)ans = ans.next;
return (ans==null)?new Node(0):ans;
}
static Node reverseList(Node head) {
if (head == null || head.next == null)return head;
Node prev = null , curr = head , next = null;
while(curr != null) {
next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}
}