1. 程式人生 > >2.兩數相加(Add Two Numbers) C++

2.兩數相加(Add Two Numbers) C++

第一想法是順著題目的原因,將兩連結串列分別轉化為一個數字,再將數字相加,然後把結果轉化為字串,存到答案連結串列中。但是資料太大會溢位!

所以,要在計算一對數字的過程當中直接儲存一個結果,注意結果大於9時進位,刪去最終連結串列的最後一個節點。

/**
 * 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 carry=0; int x,y,z; ListNode* head = new ListNode(-1); ListNode* use = new ListNode(-1); ListNode* t = new ListNode(-1); head->next = t; while(l1 || l2) {
if(!l1) { x = 0; }else x = l1->val; if(!l2) { y = 0; }else y = l2->val; z = x + y + carry; carry = 0; if(z>9) { carry = 1; z
= z-10; } t->val = z; t->next = new ListNode(-1); use = t; t = t->next; t->next = NULL; if(l1) { l1 = l1->next; } if(l2) { l2 = l2->next; } } if(carry) { t->val = carry; t->next = new ListNode(-1); use = t; t = t->next; t->next = NULL; } t = head->next; use->next = NULL; return t; } };