實作 list 類別,模擬 std::list 核心功能:動態配置節點、深拷貝建構/指派、插入/刪除任意位置、轉字串、排序。重點驗證指標操作、記憶體無洩漏、邊界條件處理。
list.hpp)struct node {
int data;
node* next;
node(int d=0, node* n=nullptr) : data(d), next(n) {}
};
class list {
node* head;
int _size;
public:
list(); // 預設建構
list(const list&); // 拷貝建構
list& operator=(const list&); // 複製指派
~list(); // 解構
bool empty() const;
int size() const;
string toString() const; // "1->2->3->NULL"
void insert(int pos, const int& val);
void erase(int pos);
void clear();
list& sort(); // 升序排序
};
head 指標 → 兩物件共享節點 → 雙重釋放崩潰。new 新節點,複製資料 → 獨立記憶體。list& list::operator=(const list& rhs) {
if (this != &rhs) { // 自我指派檢查
clear(); // 釋放舊資源
if (rhs.head) {
head = new node(rhs.head->data); // 複製首節點
node* dst = head;
for (node* src = rhs.head->next; src; src = src->next) {
dst->next = new node(src->data);
dst = dst->next;
}
}
_size = rhs._size;
}
return *this; // 返回 *this 支援鏈式指派
}
| 操作 | 特殊情況 | 處理 |
|---|---|---|
| insert(0, val) | 空表 / 非空表頭插 | 新節點 next=head; head=新節點 |
| insert(pos>0) | pos == size (尾插) | 遍歷至 pos-1,插在其後 |
| erase(0) | 刪除頭節點 | head=head->next; delete 舊頭 |
| erase(pos>0) | 中間/尾刪除 | 遍歷至 pos-1,跳過目標節點並 delete |