Cannot reverse linked list, but want to add from the end of this linked list: Use a Stack.

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
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
Stack<ListNode> st1 = new Stack<>();
Stack<ListNode> st2 = new Stack<>();
while (l1 != null) {
st1.push(l1);
l1 = l1.next;
}
while (l2 != null) {
st2.push(l2);
l2 = l2.next;
}
ListNode res = new ListNode(0);
int sum = 0;
while (!st1.empty() || !st2.empty()) {
if (!st1.empty()) sum += st1.pop().val;
if (!st2.empty()) sum += st2.pop().val;
res.val = sum % 10;
ListNode head = new ListNode(sum / 10);
head.next = res;
res = head;
sum /= 10;
}
return res.val == 0 ? res.next : res;
}
}