首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> C++ 入門

C++ 動態鏈表綜合練習:建立、查找、刪除與有序插入

     編輯:C++ 入門

練習系列概覽

六個遞進項目:尾插建表、查找、刪除首節點、刪除指定值、建有序表、有序插入。每步提供參考代碼,強調指針操作邏輯。

核心代碼模式

struct Node { int data; Node* next; };
Node* head = nullptr;

// 1. 尾插建表
void make_list2() {
    int n; Node *p, *q = nullptr;
    while (cin >> n, n > 0) {
        p = new Node; p->data = n; p->next = nullptr;
        if (!head) head = p;
        else q->next = p;
        q = p;
    }
}

// 2. 查找
void search(int x) {
    for (Node* p = head; p; p = p->next)
        if (p->data == x) { cout << "找到 " << x; return; }
    cout << "未找到 " << x;
}

// 3. 刪除首節點
void delete_first() {
    if (head) { Node* p = head; head = head->next; delete p; }
}

// 4. 刪除所有值為 x 的節點
void delete_node(int x) {
    while (head && head->data == x) { Node* p = head; head = head->next; delete p; }
    for (Node *p = head, *q = p ? p->next : nullptr; q; ) {
        if (q->data == x) { p->next = q->next; delete q; q = p->next; }
        else { p = q; q = q->next; }
    }
}

// 5. 有序建表(遞增)
void make_list3() {
    int n; while (cin >> n, n > 0) insert(n); // 復用 insert
}

// 6. 有序插入
void insert(int x) {
    Node *t = new Node; t->data = x; t->next = nullptr;
    if (!head || x <= head->data) { t->next = head; head = t; return; }
    Node *p = head, *q = head->next;
    while (q && x > q->data) { p = q; q = q->next; }
    t->next = q; p->next = t;
}

指針操作心法

  1. 畫圖:紙上畫節點盒子與箭頭,理清 p、q、t 指向。
  2. 邊界:空表、首節點、尾節點、連續目標值。
  3. 內存:new 分配,delete 釋放,避免洩漏與野指針。

測試數據建議

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