LeetCode 2. Add Two Numbers [Medium]

链表加法。

题目来源:https://leetcode.com/problems/add-two-numbers

题目难度:Medium

解答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
/**
* 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) {
ListNode dummyHead = new ListNode(0);
ListNode p1 = l1;
ListNode p2 = l2;
ListNode result = dummyHead;
int carry = 0;
int sum;

while (p1 != null || p2 != null) {
int x = (p1 != null) ? p1.val : 0;
int y = (p2 != null) ? p2.val : 0;
sum = x + y + carry;
carry = sum / 10;
result.next = new ListNode(sum % 10);
result = result.next;
if (p1 != null) {
p1 = p1.next;
}
if (p2 != null) {
p2 = p2.next;
}
}
if (carry > 0) {
result.next = new ListNode(carry);
}

return dummyHead.next;
}
}

进阶:链表中的数是正向存储的

思路1:给较短链表的长度和较长链表的长度补齐,补的高位节点的值都设为0。