刪除頭節點時,curr->pre 為 NULL,執行 (curr->pre)->next = curr->next 導致空指標解引用。
struct Student {
long num; char name[20]; char sex[10];
int age; char phone[11];
Student *next, *pre;
};
Student *head = new Student(); // 虛擬頭節點
Student *tail = new Student(); // 虛擬尾節點
head->next = tail; tail->pre = head;
void Delete(int num) {
Student *curr = head->next;
while (curr != tail) {
if (curr->num == num) {
curr->pre->next = curr->next;
curr->next->pre = curr->pre;
delete curr;
break;
}
curr = curr->next;
}
}
見原回答,已重構 creat()、print()、Delete() 統一使用虛擬頭尾節點,消除特殊邊界判斷。