-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAddTwoNumbers.java
More file actions
100 lines (90 loc) · 3.04 KB
/
Copy pathAddTwoNumbers.java
File metadata and controls
100 lines (90 loc) · 3.04 KB
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
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class MySolution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
// Create two stacks, one for each list
Stack<ListNode> stack1 = new Stack<>();
Stack<ListNode> stack2 = new Stack<>();
// Create two maps for parents, one for each list
Map<ListNode, ListNode> parents1 = new HashMap<>();
// Populate the structures
parents1.put(l1, null);
while (l1 != null) {
stack1.push(l1);
if (l1.next != null) {
parents1.put(l1.next, l1);
}
l1 = l1.next;
}
while (l2 != null) {
stack2.push(l2);
l2 = l2.next;
}
// Get head
ListNode head = stack1.peek();
// pop from stacks and add values
while (!stack1.isEmpty() && !stack2.isEmpty()) {
ListNode node = stack1.peek();
int sum = node.val + stack2.peek().val;
if (sum > 9) {
node.val = sum % 10;
ListNode cur = node;
if (parents1.get(cur) == null) {
ListNode newHead = new ListNode(1, head);
parents1.replace(head, newHead);
parents1.put(newHead, null);
}
while (parents1.get(cur).val > 9) {
if (parents1.get(parents1.get(cur)) == null) {
ListNode newHead = new ListNode(1, head);
parents1.replace(head, newHead);
parents1.put(newHead, null);
head = newHead;
newHead = null;
}
cur = cur.next;
}
if (parents1.get(head) == null) {
cur.val++;
}
}
else {
stack1.pop().val += stack2.pop().val;
}
}
return head;
}
}
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode dummyHead = new ListNode(0);
ListNode tail = dummyHead;
int carry = 0;
while (l1 != null || l2 != null || carry != 0) {
int digit1 = (l1 != null) ? l1.val : 0;
int digit2 = (l2 != null) ? l2.val : 0;
int sum = digit1 + digit2 + carry;
int digit = sum % 10;
carry = sum / 10;
ListNode newNode = new ListNode(digit);
tail.next = newNode;
tail = tail.next;
l1 = (l1 != null) ? l1.next : null;
l2 = (l2 != null) ? l2.next : null;
}
ListNode result = dummyHead.next;
dummyHead.next = null;
return result;
}
}