2. 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 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.
Example:

1
2
3
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

两个链表求和结果保存到一个翻转的链表中.

实现

  • java

定义结果链表和一个指向该链表的引用 cur,cur 表示当前正在处理的结点.

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
public ListNode (ListNode p, ListNode q){
ListNode result = new ListNode(0);
int big = 0 ;
ListNode cur = result;
while(p != null || q != null){
int a = p == null ? 0 : p.val;
int b = q == null ? 0 : q.val;
int val = a + b + big;
if (val >= 10){
val -= 10;
big = 1;
} else {
big = 0;
}
ListNode cld = new ListNode(val);
cur.next = cld;
cur = cur.next;
if (p != null){
p = p.next;
}
if (q != null){
q = q.next;
}
}
if (big > 0) {
cur.next = new ListNode(big);
}
return result.next;
}

参考资料