题目:
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:
Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 8 -> 0 -> 7
题目大意:
给了两个非空的链表,用来代表两个非负整数,数字最高位在链表开始位置,每个节点只存储单个数字,两个数字相加会返回一个新的链表。
除了数字0之外,两个数字都不会以零开头。
注:不能对两个链表操作,比如不能反转链表。
解题思路:
这种相加的思路是带有进位的加法操作,所以需要将最低位的数字首先找到,然后从右往左运算,所以需要一个栈用来存储数字,方便首先取到低位和算出进位。
相似的题目是2.链表中两数倒序相加。那个题和本题非常相似,但那个题中数字是高位在右,低位在左,所以可以直接找到低位,算出进位,而本题不行,所以需要栈的辅助。而且之后还要保持高位在左,低位在右,还需要使用头插法。
代码: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
30Java:
public ListNode addTwoNumbers(ListNode l1,ListNode l2){
Stack<Integer> l1Stack = buildStack(l1);
Stack<Integer> l2Stack = buildStack(l2);
ListNode head = new ListNode(-1);
int carry = 0;
while(!l1Stack.isEmpty() || !l2Stack.isEmpty() || carry != 0){ // carry != 0表明和是由三部分组成的,缺一不可
//比如样例中[5]和[5],结果是[1,0]而不是[0]
int x = l1Stack.isEmpty() ? 0 : l1Stack.pop();
int y = l2Stack.isEmpty() ? 0 : l2Stack.pop();
int sum = x + y + carry;
//使用头插法,保持依次算出的高位在左,低位在右
ListNode node = new ListNode(sum%10);
node.next = head.next;
head.next = node;
carry = sum / 10;
}
return head.next;
}
private Stack<Integer> buildStack(ListNode l){
Stack<Integer> stack = new Stack<>();
while(l != null){
stack.push(l.val);
l = l.next;
}
return stack;
}