leetcode 2 Add Two Numbers(链表)

数字反过来这个没有什么麻烦,就是镜像的去算十进制加法就可以了,然后就是简单的链表。

/**
 * 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 Ans(0);
        ListNode *p=&Ans;
        int more=0;
        while(l1||l2||more){
            int x=(l1?l1->val:0)+(l2?l2->val:0)+more;
            if(l1) l1=l1->next;
            if(l2) l2=l2->next;
            more=x/10;
            p->next=new ListNode(x%10);
            p=p->next;
        }
        return Ans.next;
    }
};

 

posted @ 2015-10-28 19:36  周洋  阅读(193)  评论(0编辑  收藏  举报