[英]Segmentation Fault in C++: sorted linked list
我正在編寫一個 function 以在 C++ 的排序鏈表中插入一個數字。 但是,當我運行它時,我得到了“分段錯誤”。 誰能解釋為什么會這樣?
Node * insertInSorted(Node * head, int data)
{
Node * curr = head;
Node * a = new Node(data);
while(curr->next->data < a->data || curr->next != NULL)
{
curr = curr->next;
}
Node * temp = curr->next;
curr->next = a;
a->next = temp;
return head;
}
while(curr->next->data < a->data || curr->next != NULL)
這顯然是錯誤的。 你想要的條件是:
while(curr->next != NULL && curr->next->data < a->data)
data
的data
。 function 仍然無法正常工作(你永遠不會在head
之前插入任何東西,即使那是應該發生插入的地方),但至少你的崩潰應該消失了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.