20191019-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 *ListHead=new ListNode(0);	//新建鏈表並調用構造函數初始化
        ListNode *curr=ListHead;
        int sum=0,carry=0;
        while(l1||l2)
        {
            sum=0;
            if(l1)
            {
                sum+=l1->val;
                l1=l1->next;
            }
            if(l2)
            {
                sum+=l2->val;
                l2=l2->next;
            }
            sum=sum+carry;
            carry=sum/10;
            curr->next=new ListNode(sum%10);
            curr=curr->next;
        }
        if(carry>0)
        {
            curr->next=new ListNode(carry);
        }
        return ListHead->next;
    }

};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章