• 445 Add Two Numbers II 两数相加 II


    给定两个非空链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储单个数字。将这两数相加会返回一个新的链表。
    你可以假设除了数字 0 之外,这两个数字都不会以零开头。
    进阶:
    如果输入链表不能修改该如何处理?换句话说,你不能对列表中的节点进行翻转。
    示例:
    输入: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
    输出: 7 -> 8 -> 0 -> 7
    详见:https://leetcode.com/problems/add-two-numbers-ii/description/

    C++:

    /**
     * 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) {
            stack<int> s1, s2;
            while (l1) 
            {
                s1.push(l1->val);
                l1 = l1->next;
            }
            while (l2)
            {
                s2.push(l2->val);
                l2 = l2->next;
            }
            int sum = 0;
            ListNode *res = new ListNode(0);
            while (!s1.empty() || !s2.empty())
            {
                if (!s1.empty())
                {
                    sum += s1.top(); 
                    s1.pop();
                }
                if (!s2.empty()) 
                {
                    sum += s2.top();
                    s2.pop();
                }
                res->val = sum % 10;
                ListNode *head = new ListNode(sum / 10);
                head->next = res;
                res = head;
                sum /= 10;
            }
            return res->val == 0 ? res->next : res;
        }
    };
    

     参考:https://www.cnblogs.com/grandyang/p/6216480.html

  • 相关阅读:
    poj 1113 Wall 凸包的应用
    NYOJ 78 圈水池 (入门级凸包)
    Monotone Chain Convex Hull(单调链凸包)
    poj Sudoku(数独) DFS
    poj 3009 Curling 2.0(dfs)
    poj 3083 Children of the Candy Corn
    Python join()方法
    通过FISH和下一代测序检测肺腺癌ALK基因融合比较
    华大病原微生物检测
    NGS检测ALK融合大起底--转载
  • 原文地址:https://www.cnblogs.com/xidian2014/p/8900589.html
Copyright © 2020-2023  润新知