[面试真题] LeetCode: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) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(!l1){
            return l2;
        }
        if(!l2){
            return l1;
        }
        ListNode *p = l1, *q = l2;
        int carry = 0, r = 0;
        r = p->val + q->val + carry;
        p->val = r%10;
        carry = r/10;
        while(p->next && q->next){
            p = p->next;
            q = q->next;
            r = p->val + q->val + carry;
            p->val = r%10;
            carry = r/10;
        }
        while(p->next){
            p = p->next;
            r = p->val + carry;
            p->val = r%10;
            carry = r/10;
        }
        while(q->next){
            q = q->next;
            r = q->val + carry;
            p->next = new ListNode(r%10);
            p = p->next;
            carry = r/10;
        }
        if(carry>0){
            p->next = new ListNode(1);
        }
        return l1;
    }
};

Run Status: Accepted!
Program Runtime: 192 milli secs

Progress: 1555/1555 test cases passed.
posted @ 2013-05-14 14:18  infinityu  阅读(336)  评论(0编辑  收藏  举报