1. 程式人生 > >LeetCode 2. Add Two Numbers

LeetCode 2. Add Two Numbers

問題:兩個數字逆序存在兩個連結串列中,返回兩數之和的連結串列

最開始想著轉換成數字加起來再存到連結串列了,顯然,溢位了,改成一位一位操作,邊加邊存

(以前沒寫過連結串列,寫的又長又醜,最後跑的也很慢)

C++:

/**
 * 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) {
        int idx = 0;
        idx = (l1->val+l2->val)/10;
        ListNode *ans = new ListNode((l1->val+l2->val)%10);
        ListNode *pre = ans;
        l1 = l1->next;
        l2 = l2->next;
        while((l1!=NULL)||(l2!=NULL)||idx){
            int x = l1==NULL?0:l1->val;
            int y = l2==NULL?0:l2->val;
            int res = x+y+idx;
            idx = res/10;
            res = res%10;
            ListNode *temp = new ListNode(res);
            pre->next = temp;
            pre = temp;
            if(l1) l1 = l1->next;
            if(l2) l2 = l2->next;
        }
        return ans;
    }
};