public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode p1 = l1, p2 = l2, result = new ListNode(0);
ListNode p = result;
int carr = 0;
while(p1 != null || p2 != null || carr > 0)
{
int sum = carr;
sum += p1 == null ? 0 : p1.val;
sum += p2 == null ? 0 : p2.val;
p.next = new ListNode(sum % 10);
p = p.next;
carr = sum / 10;
if(p1 != null)
p1 = p1.next;
if(p2 != null)
p2 = p2.next;
}
return result.next;
}
改進(jìn)代碼
public ListNode addTwoNumbers( ListNode l1 , ListNode l2 ){
//目標(biāo)鏈
ListNode result = new ListNode( 0 );
//指向目標(biāo)鏈的可操作鏈(因?yàn)椴荒芷茐脑瓉?lái)的鏈)
ListNode p = result;
int sum = 0;
//只要兩條鏈中有一條鏈不為空旅赢,或者結(jié)果還有進(jìn)位。就要一直循環(huán)
while( l1 != null || l2 != null || sum > 0){
//兩個(gè)鏈的值,直接相加
sum += l1 == null ? 0 : l1.val;
sum += l2 == null ? 0 : l2.val;
//取得末尾的數(shù)字,并且將其拋棄罪佳,形如 345 -> 34
p.next = new ListNode( sum % 10 );
p = p.next;
sum = sum / 10;
if( l1 != null ){
l1 = l1.next;
}
if( l2 != null ){
l2 = l2.next;
}
}
return result.next;
}