[LeetCode]:Add Two Numbers

Describe

  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

Analyse

  題目的意思就是給兩個單鏈表,然後將其中的整數相加,考慮進位,也就是題目Input中的4+6結果爲10,所以結果爲0然後向前面進1.因爲要考慮的問題是兩個鏈表的長度可能不相同,所以需要特別考慮一下。

Code

/**
 * 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 *head = NULL,*t = NULL;
        int carry = 0;
        int val1 = 0,val2 = 0,val = 0;
        while(l1||l2){
            if(l1)
                val1 = l1->val;
            else
                val1 = 0;
            if(l2)
                val2 = l2->val;
            else
                val2 = 0;
            int result = val1 + val2 + carry;
            carry = result/10;
            val = result%10;
            ListNode *node = new ListNode(val);
            if(!head)
                head = node;
            if(t)
                t->next = node;
            t = node;
            if(l1)
                l1 = l1->next;
            if(l2)
                l2 = l2->next;
        }
        if(carry){
            ListNode *node = new ListNode(carry);
            t->next = node;
        }
        return head;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章