[英]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;
}
}
}
我正在嘗試使用冒泡排序對雙鏈表進行排序,但出現運行時錯誤“進程終止,狀態為-1073741819”。 我不確定兩個if語句是否一定在循環中,但是我認為有必要跟蹤鏈表的頭和尾。 因此,我認為問題是由於邏輯錯誤造成的,但我無法弄清楚問題出在哪里。
您需要在此處檢查空指針:
Node *currNode = this->head;
while(currNode->next)
其他一切似乎都很好。
另外,如果在Windows上,還需要在適當的環境(如VS)中以調試模式運行,以查看錯誤的出在哪里。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.