LintCode 221. Add Two Numbers II

原題

LintCode 221. Add Two Numbers II

Description

You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in forward order, such that the 1's digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list.

Example

Given 6->1->7 + 2->9->5. That is, 617 + 295.

Return 9->1->2. That is, 912.

解題

題意是給定兩個(gè)用鏈表表示的數(shù),鏈表中的每個(gè)節(jié)點(diǎn)是數(shù)字的一位,第一個(gè)節(jié)點(diǎn)是數(shù)的最高位。求兩個(gè)數(shù)的和。

問題主要在于,要從最后一位開始加法和進(jìn)位的話,無(wú)法獲取前面數(shù)位的引用。

所以可以利用棧的思想對(duì)鏈表進(jìn)行“反向”,然后正常計(jì)算即可。

代碼

class Solution {
public:
    /*
    * @param l1: The first list.
    * @param l2: The second list.
    * @return: the sum list of l1 and l2.
    */
    ListNode * addLists2(ListNode * l1, ListNode * l2) {
        // write your code here
        ListNode *ans = nullptr;
        stack<int> stack1, stack2;
        while (l1 != nullptr) {
            stack1.push(l1->val);
            l1 = l1->next;
        }
        while (l2 != nullptr) {
            stack2.push(l2->val);
            l2 = l2->next;
        }
        stack<int> &s1 = stack1.size() >= stack2.size() ? stack1 : stack2;
        stack<int> &s2 = stack1.size() >= stack2.size() ? stack2 : stack1;
        while (!s1.empty()) {
            int a, b;
            a = s1.top();
            s1.pop();
            if (s2.size()) {
                b = s2.top();
                s2.pop();
            } else {
                b = 0;
            }
            int sum = a + b;
            int carry = sum / 10;
            ListNode *temp = ans;
            ans = new ListNode(sum % 10);
            ans->next = temp;
            if (carry > 0) {
                if (s1.empty()) {
                    ListNode *temp = ans;
                    ans = new ListNode(carry);
                    ans->next = temp;
                } else {
                    s1.top() += carry;
                }
            }
        }
        return ans;
    }
};
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問題, 分享了一些自己做題目的經(jīng)驗(yàn)。 張土汪:刷leetcod...
    土汪閱讀 12,936評(píng)論 0 33
  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 11,259評(píng)論 0 23
  • 原題 假定用一個(gè)鏈表表示兩個(gè)數(shù),其中每個(gè)節(jié)點(diǎn)僅包含一個(gè)數(shù)字。假設(shè)這兩個(gè)數(shù)的數(shù)字順序排列,請(qǐng)?jiān)O(shè)計(jì)一種方法將兩個(gè)數(shù)相加...
    Jason_Yuan閱讀 668評(píng)論 0 0
  • 最近小寶洗完澡總是要求我把浴缸里的水留著,不要倒掉。而且一直強(qiáng)調(diào)晚上睡覺了也不可以倒掉。每次我都保證他絕對(duì)不倒掉,...
    小花媽媽媽閱讀 294評(píng)論 0 0
  • 多年前,馬云說(shuō):“客戶第一、員工第二、股東第三”。更重要的是在接下來(lái)的十幾年里,他在無(wú)數(shù)的演講場(chǎng)合反復(fù)地重申這個(gè)理...
    Tenly閱讀 748評(píng)論 0 0

友情鏈接更多精彩內(nèi)容