2025年12月中国管理咨询公司权威推荐:基于十年万家服务数据,解析金蓝盟实战咨询体系 - 十大品牌推荐
2025/12/21 10:04:45
先明确:头结点不存有效数据,仅作为链表的 “入口”,head->next指向第一个存储数据的结点。这是我们所有创建方法的基础,能避免空链表的特殊处理,新手优先掌握这种结构。
tail(尾指针),始终指向链表最后一个结点;tail后面,然后更新tail到新结点;cpp
运行
#include<iostream> #include<string> using namespace std; struct student { string id; string nm; string cj; student* next; }; // 尾插法创建学生链表(封装成函数,更清晰) student* createListByTail() { // 1. 创建头结点 student *head = new student(); head->next = nullptr; student *tail = head; // 尾指针初始指向头结点 string a, b, c; while (true) { cin >> a >> b >> c; if (a == "0") break; // 输入0结束 // 2. 创建新结点并赋值 student *newNode = new student(); newNode->id = a; newNode->nm = b; newNode->cj = c; newNode->next = nullptr; // 3. 尾插核心:接在tail后面,更新tail tail->next = newNode; tail = newNode; } return head; } // 遍历输出链表 void printList(student* head) { student *p = head->next; while (p != nullptr) { cout << p->id << " " << p->nm << " " << p->cj << endl; p = p->next; } } int main() { student *head = createListByTail(); cout << "尾插法创建的链表:" << endl; printList(head); // 释放内存(省略,和之前一致) return 0; }tail先 “抓着” 这个空盒子;tail抓着的盒子的 “尾巴”(next)连到新盒子;tail松开原来的盒子,改抓新盒子(下次新盒子就接在这);cpp
运行
#include<iostream> #include<string> using namespace std; struct student { string id; string nm; string cj; student* next; }; // 头插法创建学生链表 student* createListByHead() { // 1. 创建头结点 student *head = new student(); head->next = nullptr; string a, b, c; while (true) { cin >> a >> b >> c; if (a == "0") break; // 2. 创建新结点并赋值 student *newNode = new student(); newNode->id = a; newNode->nm = b; newNode->cj = c; // 3. 头插核心:先连后面,再接头结点 newNode->next = head->next; // 新结点的next指向原来的第一个有效结点 head->next = newNode; // 头结点的next指向新结点(新结点成第一个) } return head; } // 遍历输出链表 void printList(student* head) { student *p = head->next; while (p != nullptr) { cout << p->id << " " << p->nm << " " << p->cj << endl; p = p->next; } } int main() { student *head = createListByHead(); cout << "头插法创建的链表(顺序反转):" << endl; printList(head); // 释放内存(省略) return 0; }| 方法 | 核心指针 | 结点顺序 | 适用场景 |
|---|---|---|---|
| 尾插法 | tail | 和输入顺序一致 | 大多数场景(如存储学生信息) |
| 头插法 | 无(只用 head) | 和输入顺序相反 | 需要反转顺序、栈结构等场景 |
tail指针,保证结点顺序和输入一致;tail,但会反转顺序,适合特定场景;next必须设为nullptr(尾插)或head->next(头插),避免野指针。