链表专题—LeetCode 2.Add Two Numbers

解题思路:
1、输入为两个用链表存储的逆序数,输出也为逆序,因此不用将输入转化为正序。
2、从两个链表的头结点开始依次相加,存储到新链表中。
3、注意计算进位。

注意:
1、输入数字很大,要使用大数加法进行计算。
2、两个链表可以不一样长。

class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {

        bool flag = false;
        ListNode *head = NULL;
        ListNode *p = NULL;
        int sum = 0;
        int carry = 0;
        while (l1 != NULL||l2 != NULL){
            int x = (l1 != NULL) ? l1->val : 0;
            int y = (l2 != NULL) ? l2->val : 0;
            sum = x + y + carry;
            if (!flag){
                head = new ListNode(sum % 10);
                p = head;
                flag = true;
            }
            else{
                ListNode *new_node = new ListNode(sum % 10);
                p->next = new_node;
                p = p->next;
            }
            carry = sum / 10;
            if (l1 != NULL)l1 = l1->next;
            if (l2 != NULL)l2 = l2->next;
        }
        if (carry != 0){
            ListNode *new_node = new ListNode(carry);
            p->next = new_node;
            p = p->next;
        }
        return head;
    }


};

猜你喜欢

转载自blog.csdn.net/daidaihema/article/details/80354866