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) {
        //边加边制造节点就ok了
        ListNode* head = new ListNode(0);
        ListNode* now=head;
        int ad=0,temp=0,temp1=0,x=0,y=0;
        int flag=0;
        while(l1!=NULL || l2!=NULL ){
             x= l1!=NULL?l1->val:0;
            y= l2!=NULL?l2->val:0;
            
            temp = x+y+flag;
            if(temp>=10) flag=1;
            else flag=0;
           
            temp1=temp%10;
            
            now->next = new ListNode(temp1);
            now=now->next;
            if(l1)l1=l1->next;
            if(l2)l2=l2->next;
        }
        if(flag>0){
            now->next=new ListNode(flag);
        }
         return head->next;
    }
};
发布了35 篇原创文章 · 获赞 5 · 访问量 2435

猜你喜欢

转载自blog.csdn.net/qq_24884193/article/details/100163866