LinkedList a;
a.headinsert(d); // 頭插 d
a.backinsert(c); // 尾插 c,結果 d 被覆蓋,只剩 c
headinsert 未更新 tail 指針,導致鏈表尾部丟失。首次頭插時 head 指向新節點,但 tail 仍為 nullptr;隨後尾插判斷 tail != nullptr 失敗,走 else head = t 覆蓋頭節點。
void headinsert(const StudentNode& stu) {
StudentNode* t = new StudentNode(stu);
t->next = head;
head = t;
if (tail == nullptr) { // 關鍵:首個節點時 tail 也指向它
tail = t;
}
}
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)。