链表相加(Add Two Numbers)

描述:

给定两个非空的链表,表示两个非负整数。数字以相反的顺序存储,每个节点包含一个数字。添加两个数字并将其作为链表返回。

您可以假设两个数字不包含任何前导零,除了数字0本身。

输入:(2 - > 4 - > 3)+(5 - > 6 - > 4)
输出: 7 - > 0 - > 8

类似于:342+564 = 807

LeetCode解决方案:

public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    ListNode dummyHead = new ListNode(0);
    ListNode p = l1, q = l2, curr = dummyHead;
    int carry = 0;
    while (p != null || q != null) {
        int x = (p != null) ? p.val : 0;
        int y = (q != null) ? q.val : 0;
        int sum = carry + x + y;
        carry = sum / 10;
        curr.next = new ListNode(sum % 10);
        curr = curr.next;
        if (p != null) p = p.next;
        if (q != null) q = q.next;
    }
    if (carry > 0) {
        curr.next = new ListNode(carry);
    }
    return dummyHead.next;
}

 我的方法:

class Solution {
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            ListNode dummyHead = new ListNode(0);
            ListNode p = l1, q = l2, curr = dummyHead;
            int carry = 0;
            while (true) {
                //做相加
                int x = (p != null) ? p.val : 0;
                int y = (q != null) ? q.val : 0;
                int sum = carry + x + y;
                curr.val = sum % 10;
                //重新赋值carry、p、q和curr
                carry = sum / 10;
                
                if (p != null) p = p.next;
                if (q != null) q = q.next;
                if(p == null && q == null) break;
               
                curr.next = new ListNode(0);
                curr = curr.next;
               
                }
            if (carry > 0) {
                curr.next = new ListNode(carry);
                }
            return dummyHead;
        }
    }
posted @ 2017-10-12 09:16  K_artorias  阅读(473)  评论(1编辑  收藏  举报