1. 程式人生 > >代碼題(11)— 鏈表兩數相加

代碼題(11)— 鏈表兩數相加

head listnode 進階 方式 pub nod solution () 如何

1、2. 兩數相加

給定兩個非空鏈表來表示兩個非負整數。位數按照逆序方式存儲,它們的每個節點只存儲單個數字。將兩數相加返回一個新的鏈表。

你可以假設除了數字 0 之外,這兩個數字都不會以零開頭。

示例:

輸入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
輸出:7 -> 0 -> 8
原因:342 + 465 = 807/**
/**
 * 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* res = new ListNode(-1); ListNode* head = res; int carry = 0; while(l1 || l2 || carry) { int sum = 0; if(l1) { sum += l1->val; l1
= l1->next; } if(l2) { sum += l2->val; l2 = l2->next; } sum = sum + carry; head->next = new ListNode(sum%10); //當前節點值 head = head->next; carry = sum/10; //進位值 }
return res->next; } };
2、445. 兩數相加 II

給定兩個非空鏈表來代表兩個非負整數。數字最高位位於鏈表開始位置。它們的每個節點只存儲單個數字。將這兩數相加會返回一個新的鏈表。

你可以假設除了數字 0 之外,這兩個數字都不會以零開頭。

進階:

如果輸入鏈表不能修改該如何處理?換句話說,你不能對列表中的節點進行翻轉。

示例:

輸入: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
輸出: 7 -> 8 -> 0 -> 7
/**
 * 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) {
        stack<int> s1, s2;
        while(l1)
        {
            s1.push(l1->val);
            l1 = l1->next;
        }
        while(l2)
        {
            s2.push(l2->val);
            l2 = l2->next;
        }
        
        ListNode* res = new ListNode(0);
        int sum = 0;
        while(!s1.empty() || !s2.empty())
        {
            if(!s1.empty())
            {
                sum += s1.top();
                s1.pop();
            }
            if(!s2.empty())
            {
                sum += s2.top();
                s2.pop();
            }
            res->val = sum%10;
            ListNode* head = new ListNode(sum/10);
            head->next = res;  //新增加的節點在前面插入
            res = head;
            sum /= 10;
        }
        return res->val == 0 ? res->next:res;
    }
};

 

代碼題(11)— 鏈表兩數相加