leetcode-445-Add-Two-Numbers-II

描述


You are given two non-empty linked lists representing two non-negative integers. 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.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.

Example:

1
2
Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 8 -> 0 -> 7

分析


两个链表相加,然而最高位在链表首位,题目又要求不能翻转链表,可以用先进后出队列解决。

解决方案1(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
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int carry = 0;
Deque<ListNode> deque1 = new LinkedList<>(), deque2 = new LinkedList<>();
ListNode current1 = l1, current2 = l2;
while (current1 != null || current2 != null) {
if (current1 != null) {
deque1.push(current1);
current1 = current1.next;
}
if (current2 != null) {
deque2.push(current2);
current2 = current2.next;
}
}

ListNode head = new ListNode(0), tmp = null;
while(!deque1.isEmpty() || !deque2.isEmpty()) {
int n1 = deque1.isEmpty()? 0: deque1.pop().val;
int n2 = deque2.isEmpty()? 0: deque2.pop().val;
int sum = n1 + n2 + carry;
carry = sum / 10;
head.val = sum % 10;
tmp = new ListNode(0);
tmp.next = head;
head = tmp;
}
if (carry == 1) {
head.val = 1;
}
return carry == 1 ? head: head.next;
}
}

相关问题


题目来源