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

C++ 鏈表類:修正頭插法導致尾指針丟失,實現頭尾插入共存

     編輯:程式設計綜合問答

問題現象

LinkedList a;
a.headinsert(d); // 頭插 d
a.backinsert(c); // 尾插 c,結果 d 被覆蓋,只剩 c

原因分析

headinsert 未更新 tail 指針,導致鏈表尾部丟失。首次頭插時 head 指向新節點,但 tail 仍為 nullptr;隨後尾插判斷 tail != nullptr 失敗,走 else head = t 覆蓋頭節點。

修正 headinsert

void headinsert(const StudentNode& stu) {
    StudentNode* t = new StudentNode(stu);
    t->next = head;
    head = t;
    if (tail == nullptr) { // 關鍵:首個節點時 tail 也指向它
        tail = t;
    }
}

完善 backinsert

void backinsert(const StudentNode& stu) {
    StudentNode* t = new StudentNode(stu);
    if (tail != nullptr) {
        tail->next = t;
    } else {
        head = t; // 空鏈表情況
    }
    tail = t;
}

測試驗證

int main() {
    StudentRecord b("td",4), c("sb",4), d("da",4);
    LinkedList a;
    a.headinsert(d); // d
    a.backinsert(c); // d -> c
    a.backinsert(b); // d -> c -> b
    a.traverse();    // 輸出: da sb td
    return 0;
}

記憶體管理補充

  • 析構函數需遍歷釋放所有節點,防止記憶體洩漏。
  • 考慮實現 copy constructor、assignment operator (Rule of Three) 或使用 std::unique_ptr (C++11)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved