You are given two linked lists representing two non-negative numbers. 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.
1
2
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
思路分析
就是两个链表的并行遍历,并不怎么难。
肯定得遍历两个链表
两链表长度相同时,对应位置相加并将进位保留到下一次循环
两链表长度不相同时,往长度较短的链表尾部补零(最高位和现实生活中的数字恰好相反)
代码
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
39
40
41
42
43
44
45
46
47
48
49
50
/***
* 2 4 3 2 4 3 0 1 2 3 4 0
* 5 6 4 5 6 4 9 6 7 8 9 9
* ------- ------- ----------
* 7 0 8 7 0 8 9 7 9 1 4 0 1
*
* **/
public ListNode addTwoNumbers(ListNode l1, ListNode l2){