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 contain a single digit. Add the two numbers and return it as a linked list.

很重要: 为什么要prevhead两个node? 因为prev随着遍历两个链表而往后,head一直保持在res链表的最前端

只要需要记住链表最前端,就需要一个指针在最前面纪录

出了while不知道是因为l1或者l2为0导致出了while,所以有一个是null的时候就用null代替,这样“出while不知道carry是不是0”这个麻烦也没有了

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode prev = new ListNode(0);
ListNode head = prev;
int carry = 0;

while (l1 != null || l2 != null || carry != 0) {
ListNode cur = new ListNode(0);
int sum = ((l1 == null)? 0: l1.val) + ((l2 == null)? 0: l2.val) + carry;
cur.val = sum % 10;
carry = sum / 10;
prev.next = cur;
prev = cur;

l1 = (l1 == null) ? l1 : l1.next;
l2 = (l2 == null) ? l2 : l2.next;
}

return head.next;
}

Ausgezeichnet.