本题相对简单,CC上有个反过来的比较蛋疼, 这个顺着的比较好写。
这个版本写的比较长一点,但逻辑一目了然:先加两个list共同长度的部分,再把较长的加上去,最后还要check有木有进位。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if (l1 == null){
return l2;
}
if (l2 == null){
return l1;
}
int i = 0, j = 0;
ListNode current = null;
ListNode head = null;
for (;l1 != null && l2 != null; l1 = l1.next, l2 = l2.next){
int sum = l1.val + l2.val + j;
i = sum % 10;
j = sum / 10;
ListNode s = new ListNode(i);
if (head == null){
head = s;
} else {
current.next = s;
}
current = s;
}
ListNode t = (l1 != null)? l1 : l2;
for (; t != null; t = t.next){
int sum = t.val + j;
i = sum % 10;
j = sum / 10;
ListNode s = new ListNode(i);
current.next = s;
current = s;
}
if (j > 0){
ListNode s = new ListNode(j);
current.next = s;
current = s;
}
return head;
} //end of for loop
<span style="font-family: Arial, Helvetica, sans-serif;">} //end of method</span>
<span style="font-family: Arial, Helvetica, sans-serif;">}//end of class</span>
如果把上面的缩短一点,就变成这样: (如果一个list是空的,一下解法有点浪费)
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int i = 0, j = 0;
ListNode current = null;
ListNode head = null;
for (;l1 != null || l2 != null || j > 0; l1 = (l1 == null) ? null : l1.next, l2 = (l2 == null) ? null : l2.next){
int v1 = (l1 == null) ? 0 : l1.val;int v2 = (l2 == null) ? 0 : l2.val;
int sum = v1 + v2 + j;
i = sum % 10;
j = sum / 10;
ListNode s = new ListNode(i);
if (head == null){
head = s;
} else {
current.next = s;
}
current = s;
}
return head;
}
}