• (链表 importance) 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.

    Example:

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

    --------------------------------------------------------------------------------------
    这个题就是两个链表内的数字相加,注意进位、两个链表的长度并不一样还有链表是空链表特殊例子。emmm,记得几个月前面对它是一脸懵逼的,现在重新看它,却发现有点简单
    详见官方题解:
    https://leetcode.com/articles/add-two-numbers/
    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) {
            ListNode *dummy = new ListNode(-1);
            ListNode *cur = dummy;
            ListNode *p = l1;
            ListNode *q = l2;
            int carry = 0;
            while(p || q){
                int x = (p!=NULL)?p->val:0;
                int y = (q!=NULL)?q->val:0;
                int sum = carry + x + y;
                carry = sum/10;
                cur->next = new ListNode(sum % 10);
                cur = cur->next;
                if(p) p=p->next;
                if(q) q=q->next;
            }
            if(carry > 0){
                cur->next = new ListNode(carry);
            }
            return dummy->next;
        }
    };
  • 相关阅读:
    hdu 6440 Dream(费马小定理+构造)
    [POJ3107]Godfather
    [POJ2488]A Knight's Journey
    [POJ3009]Curling 2.0
    [BZOJ1040][CODEVS1423][ZJOI2008]骑士
    [BZOJ1103] [POI2007]大都市meg
    BZOJ1827 [Usaco2010 Mar]gather 奶牛大集会
    [codevs1286]郁闷的出纳员
    [codevs3044]矩形面积求并
    BZOJ4563[Haoi2016]放棋子
  • 原文地址:https://www.cnblogs.com/Weixu-Liu/p/10704746.html
Copyright © 2020-2023  润新知