(链表 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;
    }
};

猜你喜欢

转载自www.cnblogs.com/Weixu-Liu/p/10704746.html
今日推荐