LeetCode—2. Add Two Numbers

Type:medium

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse orderand 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 -> 8Explanation:342 + 465 = 807.


本题给定两个ListNode型输入结构,首先要对ListNode这个struct进行了解。这个struct中包含一个int型的val值,一个指向ListNode型的next指针,并通过构造函数定义了ListNode(int x)的返回类型。和手算加法一样,两个int数据相加时首先个位相加,若大于10则进位一位,此题同理。

此题解法为开一条链表,其中dummy指针始终指向链表头,cur指针始终指向链表尾。设carry值为0/1表示是否进位。

在遍历l1、l2链表时,要注意是否为空。若非空,则当前位val值为(l1->val+l2->val+carry)%10。注意最后一次计算若仍需进位,即carry值不为0,要新建一个ListNode型存储“1”。

最后返回dummy->next


附代码:

/**

* 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(0);

        ListNode *cur = dummy;

        int p, q;

        int carry = 0;

        while(l1 || l2){

            p = l1?l1->val:0;

            q = l2?l2->val:0;

            if(l1) l1 = l1->next;

            if(l2) l2 = l2->next;

            cur->next = new ListNode((p + q + carry)%10);

            cur = cur->next; 

            carry = (p + q + carry)/10;

        }

        if(carry != 0) {

            cur->next = new ListNode(1);

        }

        return dummy->next;

    }

};

你可能感兴趣的:(LeetCode—2. Add Two Numbers)