[LeetCode]2. Add Two Numbers

題目:

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

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
代碼:

/**
 * 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) {
         if(l1==NULL) return l2;
         if(l2==NULL) return l1;

         ListNode *resultHead = NULL ,*beforeNode = NULL;
         int carry = 0;//當前進位 
         int  a,b ;
         bool flag = l1 || l2;//只有兩個都爲NULL時,纔有可能結束
         int currentResult = 0;
         while(flag||carry){//當進位爲0且l1,l2都爲NULL時,才結束
             ListNode *resultNode = new ListNode(0);
             if(resultHead == NULL){
                  resultHead = resultNode;
                  beforeNode = resultHead;
             }
             else{
                 beforeNode->next = resultNode;
                 beforeNode = resultNode;
             }
             a = l1 ? (l1->val) : 0;//當l爲空時,將其內容當成0
             b = l2 ? (l2->val) : 0;
             currentResult = a + b + carry;
             resultNode->val = currentResult % 10;
             carry = currentResult / 10;
             //當l爲NULL時,沒有next,一定要讓其保持爲NULL
             l1 = l1 ? l1->next:l1;
             l2 = l2 ? l2->next:l2;
             flag = l1 || l2;

         }

         return resultHead;
    }
};

注:由於兩個列表可能長度不同,所以這裏採用了補齊的方法,將短列表後面的內容都當成0。

發佈了37 篇原創文章 · 獲贊 7 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章