尽管条件为真,循环仍会停止

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

我正在将2个已排序的链接列表合并为一个已排序的列表。我的代码获得了除最后一个输出以外的所有内容。

   class Solution {
    private:
        ListNode* head = NULL;
        ListNode* current1 = NULL;
        ListNode* current2 = NULL;
        ListNode* current3 = NULL;

    public:
        ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {

            setPointers(l1,l2); //  set current pointers to beginning of each list

            while((current1) && (current2)) {

                if((current1->val <= current2->val) || (current2 == NULL)) {  
                    ListNode* newNode = new ListNode;
                    newNode->val = current1->val;
                    current1 = current1->next; 

                    if(isEmpty(head)) {
                        head = newNode;
                        current3 = newNode;
                    }
                    else {
                        current3->next = newNode;
                        current3 = current3->next;
                    }
                }

                else if((current2->val <= current1->val) || (current1 == NULL)) {
                    ListNode* newNode = new ListNode;
                    newNode->val = current2->val;
                    current2 = current2->next; 

                    if(isEmpty(head)) {
                        head = newNode;
                        current3 = newNode;
                    }
                    else {
                        current3->next = newNode;
                        current3 = current3->next;
                    }
                }
            }
            return head;
        }

        bool isEmpty(ListNode* head) {
            if(head == NULL) 
                return true;
            return false;
        }

        void setPointers(ListNode* list1, ListNode* list2) {
            current1 = list1;
            current2 = list2;
        }
    };`

您的输入[1,2,4] [1,3,4]输出[1,1,2,3,4]预期的[1,1,2,3,4,4]

我以为while循环一直持续到current1和current2都为NULL,但似乎在进行最后一次比较之前就停止了。

c++ sorting pointers data-structures linked-list
2个回答
0
投票

&&运算符仅在both操作数为true时(即,在您的情况下不为null)才计算为true。一旦至少一个操作数为假,则循环停止。

您可能想要while (current1 || current2),它将在至少一个操作数不为null时循环。

编辑:另外,请注意评估顺序:

if((current1->val <= current2->val) || (current2 == NULL))

您正在访问current2,然后检查它是否不为空(&&和||条件从左开始评估,当从第一个操作数的值明显得出结果时,将发生短路)


0
投票

此表达式:

if((current1->val <= current2->val) || (current2 == NULL)) 

current2为NULL时,引起未定义的行为。您需要在取消引用之前进行检查:

if((current2 == NULL) || (current1->val <= current2->val)) 
© www.soinside.com 2019 - 2024. All rights reserved.