如果结构体中有一个本结构体的指针,它就是链表。
定义链表节点结构体
#include <iostream>
#include <string>
struct st_people {
int no;
std::string name;
st_people *next; // 指向下一个节点的指针
// 构造函数初始化数据成员
st_people(int num, std::string nm) : no(num), name(nm), next(nullptr) {}
};
示例代码
接下来,我将演示如何创建链表节点、连接它们,并遍历链表来输出信息:
int main() {
// 创建链表的头节点
st_people *head = new st_people(1, "Alice");
// 添加更多的节点到链表
head->next = new st_people(2, "Bob");
head->next->next = new st_people(3, "Carol");
// 遍历链表并打印每个节点的内容
st_people *current = head;
while (current != nullptr) {
std::cout << "No: " << current->no << ", Name: " << current->name << std::endl;
current = current->next; // 移动到下一个节点
}
// 释放链表所占用的内存
current = head;
st_people *temp;
while (current != nullptr) {
temp = current;
current = current->next;
delete temp;
}
return 0;
}
程序解释
-
链表创建:我们首先创建了一个头节点,然后依次添加更多的节点。每个节点都通过其构造函数初始化编号和姓名,并默认其
next
指针为nullptr
。 -
遍历链表:通过一个循环,我们遍历整个链表,使用
current
指针从头节点开始,直到current
变为nullptr
。在每个节点,我们打印出编号和姓名。 -
释放内存:为了防止内存泄漏,我们需要释放所有动态分配的节点。通过另一个循环,我们遍历链表,释放每个节点占用的内存。
这样的代码演示了如何在C++中操作简单的单向链表,以及如何管理动态内存,确保程序的健壮性。