【Add 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

代码

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode dummy(-1);
        ListNode *p = &dummy,*p1 = l1,*p2 = l2;
        int carry = 0;
        while(p1!=NULL || p2!=NULL){
            const int v1 = p1==NULL?0:p1->val, v2 = p2==NULL?0:p2->val, v = (v1+v2+carry)%10;
            carry = (v1+v2+carry)/10;
            p->next = new ListNode(v);
            p = p->next;
            p1 = p1==NULL ? NULL : p1->next;
            p2 = p2==NULL ? NULL : p2->next;
        }
        if ( carry > 0 ) p->next = new ListNode(carry);
        return dummy.next;
    }
};

Tips

核心在于判断while停止条件:直到l1和l2都走完了才退出;如果l1或者l2先走完了,就当该位是0。

上面这种思路的好处是可以简化代码。

=========================================

第二次过这道题,已经对思路比较熟悉了;指针定义操作什么的,稍微想了一下;代码还是一次AC。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        int carry = 0;
        ListNode* pre = new ListNode(0);
        ListNode* head = pre;
        while ( l1 || l2 )
        {
            int digit1 = l1 ? l1->val : 0;
            int digit2 = l2 ? l2->val : 0;
            int curr_val = (digit1 + digit2 + carry)%10;
            carry = (digit1 + digit2 + carry)/10;
            if ( l1 ) l1 = l1->next;
            if ( l2 ) l2 = l2->next;
            pre->next = new ListNode(curr_val);
            pre = pre->next;
        }
        if ( carry>0 ) pre->next = new ListNode(carry);
        return head->next;
    }
};

 

posted on 2015-04-28 22:02  承续缘  阅读(155)  评论(0编辑  收藏  举报

导航