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

C++ 簡單鏈表建立常見錯誤與修正

     編輯:程式設計綜合問答

原始碼問題

  1. 輸入緩衝區殘留換行符:`cin >> num` 後緩衝區留有 `\n`,導致後續 `getline(cin, nm)` 讀到空字串。
  2. 頭結點資料未初始化:`pHead = new node;` 頭結點通常不存資料,僅作哨兵。
  3. 迴圈次數硬編碼:`i <= 1` 固定 2 次,建議改為使用者決定或讀到 EOF。
  4. 記憶體洩漏:程式結束未 `delete` 所有節點。

修正版程式碼

#include 
#include 
using namespace std;

struct Node {
    int number;
    string name;
    string sex;
    int age;
    Node* next;
    Node() : number(0), age(0), next(nullptr) {}
};

void travelList(Node* head) {
    Node* p = head->next;
    while (p) {
        cout << p->number << " " << p->name << " " << p->sex << " " << p->age << endl;
        p = p->next;
    }
}

Node* createList() {
    Node* head = new Node(); // 哨兵頭結點
    Node* tail = head;
    
    int n;
    cout << "輸入節點數: ";
    cin >> n;
    cin.ignore(numeric_limits::max(), '\n'); // 清除換行
    
    for (int i = 0; i < n; ++i) {
        int num, ag;
        string nm, sx;
        
        cout << "編號: "; cin >> num; cin.ignore();
        cout << "姓名: "; getline(cin, nm);
        cout << "性別: "; getline(cin, sx);
        cout << "年齡: "; cin >> ag; cin.ignore();
        
        Node* newNode = new Node();
        newNode->number = num;
        newNode->name = nm;
        newNode->sex = sx;
        newNode->age = ag;
        
        tail->next = newNode;
        tail = newNode;
    }
    return head;
}

void freeList(Node* head) {
    while (head) {
        Node* tmp = head;
        head = head->next;
        delete tmp;
    }
}

int main() {
    Node* head = createList();
    travelList(head);
    freeList(head);
    return 0;
}

關鍵修正點

  • 每次 `cin >>` 後緊接 `cin.ignore()` 清除換行,確保 `getline` 正常。
  • 使用哨兵頭結點簡化插入邏輯。
  • 動態決定節點數,增強靈活性。
  • 提供 `freeList` 釋放記憶體,養成良好習慣。

進階建議

  • 使用 `std::unique_ptr` 管理記憶體(C++11)。
  • 封裝為 `class List` 提供 `push_back`、`begin()`/`end()` 迭代器。
  • 輸入驗證:檢查 `cin.fail()`、年齡範圍等。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved