Leetcode 2 Add Two Numbers

Leetcode 2 Add Two Numbers

You are given two non-empty linked lists representing two non-negative integers. 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.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

題意

  給出兩個逆序存放的單鏈表,算出正序後他們組成數的和,再逆序存儲。

解題思路

  由於兩個數的長度可能不一樣,所以處理的時候,可以先把重合的部分加起來,構造成新的鏈表,多出來的部分直接接上,最後再用一個循環處理進位即可。注意末尾可能會進位,這個時候需要在末尾補1。

  開始的時候,我聲明單鏈表寫的是ListNode* ans=(ListNode * )malloc(sizeof(ListNode));在線調試,閉着眼睛都能跑過後臺數據,一直報RE,後來改成ListNode* ans=new ListNode(0);就過了。

代碼

/**
 * 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* ptr=new ListNode(0);
        ListNode* ans=ptr;

        while(l1&&l2)
        {
            int tmp=(l1->val)+(l2->val);
            ListNode* p=new ListNode(0);
            p->val=tmp;
            p->next=NULL;
            ptr->next=p;
            ptr=ptr->next;

            l1=l1->next;
            l2=l2->next;
        }
        ans=ans->next;
        if(l1) ptr->next=l1;
        else ptr->next=l2;

        ListNode *car=ans,*last=ans;
        int carry=0;
        while(car)
        {
            car->val=car->val+carry;
            if((car->val)>=10)
            {
                car->val-=10;
                carry=1;
            }
            else carry=0;
            last=car;
            car=car->next;
        }

        if(carry) {
            ListNode* p=new ListNode(0);
            p->val=1;
            p->next=NULL;
            last->next=p;
        }
        return ans;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章