简体   繁体   English

对双向链表进行排序会导致运行时错误

[英]Sorting doubly linked list gives a runtime error

void Sort()
{
    //bubble sort (ascending order)
    bool unsorted = true;
    while(unsorted)
    {
        unsorted = false;
        Node *currNode = this->head;
        //iterate through all the list
        while(currNode->next)
        {
            Node *nextNode = currNode->next;
            //if nextNode < currentNode, swap
            if(nextNode->data < currNode->data)
            {
                Node *temp = currNode->prev;
                currNode->next = nextNode->next;
                currNode->prev = nextNode;
                nextNode->next = currNode;
                nextNode->prev = temp;
                //if currentNode is head, new head points to next node
                if(currNode == this->head)
                {
                    this->head = nextNode;
                }
                //if nextnode is tail, new tail points to current node
                if(nextNode == this->tail)
                {
                    this->tail = currNode;
                }
                unsorted = true;
            }
            currNode = currNode->next;
        }
    }
}

I'm trying to sort doubly linkedlist using bubble sort, and I get a runtime error 'Process terminated with status -1073741819'. 我正在尝试使用冒泡排序对双链表进行排序,但出现运行时错误“进程终止,状态为-1073741819”。 I'm not entirely sure if the two if-statements were necessarily inside the loop, but I thought it was necessary to keep track of head and tail of the linkedlist. 我不确定两个if语句是否一定在循环中,但是我认为有必要跟踪链表的头和尾。 So I think the issue is due to logical error, but I can't figure out where it went wrong. 因此,我认为问题是由于逻辑错误造成的,但我无法弄清楚问题出在哪里。

You need to check for null pointer here: 您需要在此处检查空指针:

Node *currNode = this->head;
while(currNode->next)

Everything else seems fine. 其他一切似乎都很好。

Also you need to run in debug mode in proper environment like VS if on Windows to see where the error actully is. 另外,如果在Windows上,还需要在适当的环境(如VS)中以调试模式运行,以查看错误的出在哪里。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM