(链表 importance) leetcode 2. Add Two Numbers

Posted PJCK

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了(链表 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;
    }
};

 

以上是关于(链表 importance) leetcode 2. Add Two Numbers的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode-023-合并K个升序链表

LeetCode-021-合并两个有序链表

[算法] leetcode单链表相关题目详解

LeetCode-203-移除链表元素

[JavaScript 刷题] 链表 - 相交链表, leetcode 160

[JavaScript 刷题] 链表 - 相交链表, leetcode 160