码迷,mamicode.com
首页 > 其他好文 > 详细

(链表 importance) leetcode 2. Add Two Numbers

时间:2019-04-14 13:55:29      阅读:107      评论:0      收藏:0      [点我收藏+]

标签:etc   you   链表   就是   ini   简单   linked   str   lis   

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;
    }
};

 

(链表 importance) leetcode 2. Add Two Numbers

标签:etc   you   链表   就是   ini   简单   linked   str   lis   

原文地址:https://www.cnblogs.com/Weixu-Liu/p/10704746.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!