0%

LeetCode No2 Add Two Numbers

题目

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself.

给定两个表示两个非负整数的非空链表。这些数字以相反的顺序存储,它们的每个节点都包含一个数字。将这两个数字相加并将总和作为链接列表返回。您可以假设这两个数字不包含任何前导零,除了数字 0 本身。

1
2
3
4
5
6
7
8
9
10
11
12
13
public static class ListNode {
int val;
ListNode next;
ListNode() {
}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}

示例

1
2
Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
Output: [8,9,9,9,0,0,0,1]
1
2
Input: [2,3,4],[5,6,4]
Output: [7,9,8]
1
2
Input: [2,4,4],[5,6,4]
Output: [7,0,9]

思路

新增两个相同ListNode,一个用于遍历取值,一个用于返回值。

如果val大于10,应该在next结点存为1;

解法1–自己的求解

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
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode list = new ListNode();
ListNode list2 = list;
int i;
if (l1==null && l2==null) return null;
if (l1 == null) return l2;
if (l2 == null) return l1;
for (i = 0; i<= 99;i++) {
list.val = l1.val + l2.val + list.val;
if (list.val >= 10) {
list.val = list.val - 10;
list.next = new ListNode(1);
} else {
list.next = new ListNode();
}
if (l1.next == null && l2.next == null) {
if (list.next.val == 0) {
list.next = null;
}
break;
} else if (l1.next == null) {
l1.val = 0;
l2=l2.next;
} else if (l2.next == null) {
l2.val = 0;
l1=l1.next;
} else {
l1=l1.next;
l2=l2.next;
}
list = list.next;
}
return list2;
}

缺点:考虑的特殊情况太多,判断性语句过多,导致代码冗余,没有将特殊情况归到一般情况中。

解法2-标准解法

1
2
3
4
5
6
7
8
9
10
11
12
13
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int carry = 0;
ListNode head = new ListNode(0), p = head;
while (l1 != null || l2 != null || carry != 0) {
int sum = carry;
if (l1 != null) { sum += l1.val; l1 = l1.next; }
if (l2 != null) { sum += l2.val; l2 = l2.next; }
p.next = new ListNode(sum % 10);
p = p.next;
carry = sum / 10;
}
return head.next;
}