LeetCode 2. 两数相加

题目描述:

解法:

/**
 * 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* head=new ListNode((l1->val+l2->val)%10),*temp=head;
        bool f=(l1->val+l2->val)>=10? 1:0;
        l1=l1->next;l2=l2->next;
        while(l1!=NULL&&l2!=NULL){
            temp->next=new ListNode((l1->val+l2->val+f)%10);
            temp=temp->next;
            f=(l1->val+l2->val+f)>=10? 1:0;
            l1=l1->next;l2=l2->next;
        }
        ListNode* now= l1==NULL? l2:l1;
        while(now!=NULL){
            temp->next=new ListNode((now->val+f)%10);
            temp=temp->next;
            f=(now->val+f)>=10? 1:0;
            now=now->next;
        }
        if(f==1){
            temp->next=new ListNode(1);
        }
        return head;
    }
};

 

posted @ 2019-08-31 16:12  DH_HUSTer  阅读(12)  评论(0编辑  收藏  举报