首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

C++ 雙向鏈表刪除頭節點導致崩潰?加入虛擬頭尾節點解決邊界條件

     編輯:程式設計疑難解答

崩潰原因

刪除頭節點時,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() 統一使用虛擬頭尾節點,消除特殊邊界判斷。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved