[英]Why do I get a segmentation fault from my while loop?
我正在使用鏈表在C ++中編程ADT,但由於我的一個功能似乎是while循環,所以不斷出現分段錯誤。 我嘗試自己調試它,但找不到故障的根源。
這是函數中的代碼:
void remove(int a){
cout << "remove" << endl;
node * temp;
cout << "remove 2" <<endl;
while(head->number != a){
cout << "remove 3" << endl;
head = head->next;
}
cout << "remove 4" << endl;
temp = head;
head = head->next;
delete temp;
}
Head是普通節點,其中head中的變量數是整數。 頭本身就是一個節點指針。
謝謝!
正如大家在評論中指出的那樣,您需要通過檢查head的值來檢查是否到達列表的末尾。
void remove(int a){
node * temp;
node *ptr = head;
/* Keep iterating list if {Conditional 1 - Head is not NULL && Conditional 2 - number not equal to a} */
while(ptr && ptr->number != a){
ptr = ptr->next; //Walk the linked list
}
/* Do this only if head is not NULL!! */
if(ptr != NULL) {
/* Save head pointer in temp */
temp = ptr;
/* Increment head to point to next node in list */
ptr = ptr->next;
/* Delete original item pointed to by temp */
delete temp;
}
}
理想情況下,“ head”始終指向列表的開頭(因此,將其命名為head)。 我們通常在迭代列表之前先聲明一個指向head的臨時指針。
使用數字之前,您必須檢查head是否不指向null
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.