Leetcode 2. Add Two Numbers

題目要求

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

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

例子:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

思路:

每一位相加,當前位推入鏈表,記錄進位數值,每一次的當前位都等於兩個當前位數字相加再加上進位數字。

要點:

  • 複習一下c++中地址的使用、類的定義,鏈表是最簡單的常用自定義數據類型之一了。
  • 因爲是單鏈表,沒有prev,所以既要定義起始node的地址,也要記錄node的變量名,node的地址在迭代過程中不斷在變,爲了最後還能找到起始點。
  • 比較特殊的情況就是兩個數字的位數不同,這種情況下可以在該位補0。

代碼:

/**
 * 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 StartFrom(0);
        ListNode *p = &StartFrom;
        int carry=0;
        while (l1 || l2 || carry)
        {
            int term1 = l1 ? l1->val : 0;
            int term2 = l2 ? l2->val : 0;
            int sum = term1 + term2 + carry;
            carry = sum / 10;
            int digits = sum % 10;           
            p->next = new ListNode(digits);
             p = p->next;
            l1 = l1? l1->next : 0;
            l2 = l2? l2->next : 0;
        }
        return StartFrom.next;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章