|
8 | 8 |
|
9 | 9 | /**
|
10 | 10 | * 445. Add Two Numbers II
|
| 11 | + * |
11 | 12 | * You are given two non-empty linked lists representing two non-negative integers.
|
12 | 13 | * The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
|
13 | 14 |
|
|
23 | 24 | */
|
24 | 25 | public class _445 {
|
25 | 26 |
|
26 |
| - public ListNode addTwoNumbers(ListNode l1, ListNode l2) { |
27 |
| - Deque<Integer> stack1 = popIntoStack(l1); |
28 |
| - Deque<Integer> stack2 = popIntoStack(l2); |
| 27 | + public static class Solution1 { |
| 28 | + public ListNode addTwoNumbers(ListNode l1, ListNode l2) { |
| 29 | + Deque<Integer> stack1 = popIntoStack(l1); |
| 30 | + Deque<Integer> stack2 = popIntoStack(l2); |
29 | 31 |
|
30 |
| - int sum = 0; |
31 |
| - ListNode list = new ListNode(0); |
32 |
| - while (!stack1.isEmpty() || !stack2.isEmpty()) { |
33 |
| - if (!stack1.isEmpty()) { |
34 |
| - sum += stack1.removeFirst(); |
35 |
| - } |
36 |
| - if (!stack2.isEmpty()) { |
37 |
| - sum += stack2.removeFirst(); |
| 32 | + int sum = 0; |
| 33 | + ListNode list = new ListNode(0); |
| 34 | + while (!stack1.isEmpty() || !stack2.isEmpty()) { |
| 35 | + if (!stack1.isEmpty()) { |
| 36 | + sum += stack1.removeFirst(); |
| 37 | + } |
| 38 | + if (!stack2.isEmpty()) { |
| 39 | + sum += stack2.removeFirst(); |
| 40 | + } |
| 41 | + list.val = sum % 10; |
| 42 | + ListNode head = new ListNode(sum / 10); |
| 43 | + head.next = list; |
| 44 | + list = head; |
| 45 | + sum /= 10; |
38 | 46 | }
|
39 |
| - list.val = sum % 10; |
40 |
| - ListNode head = new ListNode(sum / 10); |
41 |
| - head.next = list; |
42 |
| - list = head; |
43 |
| - sum /= 10; |
| 47 | + return list.val == 0 ? list.next : list; |
44 | 48 | }
|
45 |
| - return list.val == 0 ? list.next : list; |
46 |
| - } |
47 | 49 |
|
48 |
| - private Deque<Integer> popIntoStack(ListNode head) { |
49 |
| - ListNode tmp = head; |
50 |
| - Deque<Integer> stack = new ArrayDeque<>(); |
51 |
| - while (tmp != null) { |
52 |
| - stack.push(tmp.val); |
53 |
| - tmp = tmp.next; |
| 50 | + private Deque<Integer> popIntoStack(ListNode head) { |
| 51 | + ListNode tmp = head; |
| 52 | + Deque<Integer> stack = new ArrayDeque<>(); |
| 53 | + while (tmp != null) { |
| 54 | + stack.push(tmp.val); |
| 55 | + tmp = tmp.next; |
| 56 | + } |
| 57 | + return stack; |
54 | 58 | }
|
55 |
| - return stack; |
56 | 59 | }
|
57 | 60 |
|
58 | 61 |
|
|
0 commit comments