将两个数字添加为链接列表

问题描述 投票:2回答:1

我正在尝试添加两个数字(以链表的形式以相反的顺序表示)。我在C ++中有一个解决方案

class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        bool carry = 0;
        ListNode *head1 = l1; 
        ListNode *head2 = l2; 

        ListNode *head = nullptr;
        ListNode *curr = nullptr;

        while (head1 || head2 || carry) {
            // get value
            int val = (head1 ? head1->val : 0) +
                (head2 ? head2->val : 0) + carry;

            curr = new ListNode(val % 10);
            if (!head) head = curr;

            curr = curr->next;
            head1 = head1 ? head1->next : nullptr; 
            head2 = head2 ? head2->next : nullptr;
            carry = val / 10;
        }

        return head;
    }
};

出于某种原因,这只会返回长度为一的链表。此初始化头是否应该在第一次使用curr时使用,然后curr才能继续正确构建列表?

c++ linked-list
1个回答
0
投票

正如Ian4264和JaMiT所述,第一次进入循环时,将创建一个新节点并使其指向curr。此后,立即将curr设置为curr->next,它指向任意位置。您永远不会将curr->next指向该位置进行进一步分配。

class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        bool carry = 0;
        ListNode *head1 = l1; 
        ListNode *head2 = l2; 

        ListNode *head = nullptr;
        ListNode *curr = nullptr;

        while (head1 || head2 || carry) {
            // get value
            int val = (head1 ? head1->val : 0) +
                (head2 ? head2->val : 0) + carry;


            if (!curr){
                //first time around the loop (curr is nullptr) 
                //set curr to point to a new node
                curr = new ListNode(val % 10);
            }
            else {
                //if current was pointing to some node already, then 
                //its's next is set to point to the new allocation and curr
                //is set to the last node (just allocated) - and thus 
                //current
                curr->next = new ListNode(val % 10);
                curr = curr->next;
            }
            if (!head) head = curr;

            head1 = head1 ? head1->next : nullptr; 
            head2 = head2 ? head2->next : nullptr;
            carry = val / 10;
        }

        return head;
    }
};
© www.soinside.com 2019 - 2024. All rights reserved.