2、Two numbers
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
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode head = new ListNode(0);
ListNode p1 = l1, p2 = l2, p = head;
int c = 0;
while(p1!=null || p2!=null || c==1){ //当两个链表都已经走完,但是有进位,仍然需要新增一个节点存储进位
int add1 = (p1==null ? 0 : p1.val);//这两句写的甚好啊!判断加取值用一行代码就表示出来了!!赞!
int add2 = (p2==null ? 0 : p2.val);
int k = add1 + add2 + c;
c = k/10;
p.next = new ListNode(k%10);//头结点未用,直接存在下一个节点。新建一个节点,存值,而不是p.val = k; ListNode q=new ListNode(0);p = q;避免了最后创建一个节点但是没有使用,最后返回的head中最后一个节点的val = 0,返回结果不正确
p = p.next;
if(p1!=null){p1 = p1.next;}
if(p2!=null){p2 = p2.next;}
}
return head.next;
}
}
127

被折叠的 条评论
为什么被折叠?



