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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
这个题思路很简单,主要遇到的问题:
1.在处理链表的时候,
ListNode
temp
=
sum
; 中的temp 和sum 可以理解为指针,所以,每次新new 一个sum的话,指向的对象肯定就变化了,所以new的时候只能new ,sum.next。
2.忘了怎么处理怎么到达表头了,这个很简单,直接定义两个变量指向表头,每次只改变一个,所以另一个一直都在表头的位置。
public
class
Solution {
public
ListNode addTwoNumbers(ListNode
l1
, ListNode
l2
) {
ListNode
sum
=
new
ListNode(0);
ListNode
temp
=
sum
;
int
i
=0;
while
(
l1
!=
null
||
l2
!=
null
||
i
!=0){
if
(
l1
==
null
){
l1
=
new
ListNode(0);
}
if
(
l2
==
null
){
l2
=
new
ListNode(0);
}
if
(
sum
==
null
){
sum
=
new
ListNode(0);
}
if
(
l1
.
val
+
l2
.
val
+
i
<10){
sum
.
next
=
new
ListNode(
l1
.
val
+
l2
.
val
+
i
);
sum
=
sum
.
next
;
i
=0;
}
else
{
sum
.
next
=
new
ListNode(
l1
.
val
+
l2
.
val
+
i
-10);
sum
=
sum
.
next
;
i
=1;
}
l1
=
l1
.
next
;
l2
=
l2
.
next
;
}
return
temp
.
next
;
}
}