C++ 链表操作:删除节点示例
#include <bits/stdc++.h> using namespace std;
// 引入头文件
struct student { string name; struct student *next; // 定义链表的下一个节点 };
// 定义学生结构体,包含姓名和下一个节点的指针
void printLink(struct student *head) { struct student *p = head; while (p != NULL) { cout << p->name << '->'; // 输出当前节点的姓名 p = p->next; // 指向下一个节点 } cout << 'NULL' << endl; // 输出链表结尾 }
// 打印链表
int main() { struct student stu1, stu2, stu3, stu4, stu5, stu6, stu7, stu8;
// 定义8个学生结构体
stu1.name = '赵';
stu2.name = '钱';
stu3.name = '孙';
stu4.name = '李';
stu5.name = '周';
// 给学生结构体赋值
stu1.next = &stu2;
stu2.next = &stu3;
stu3.next = &stu4;
stu4.next = &stu5;
stu5.next = NULL;
// 将节点连接起来
struct student *head = &stu1;
// 定义头节点
printLink(head);
// 打印链表
struct student *p, *pre;
// 定义两个指针,p指向当前节点,pre指向当前节点的前一个节点
cout << '删除节点' << endl;
cout << '1.删除头节点' << endl;
head = head->next;
printLink(head);
// 删除头节点
cout << endl
<< '2.删除其它节点' << endl;
pre = head;
p = pre->next;
while (p->name != '孙')
{
pre = pre->next;
p = p->next;
}
pre->next = p->next;
printLink(head);
// 删除中间节点
return 0;
}
// 主函数,调用打印链表和删除节点函数,输出最终结果。
AI 优化版
原文地址:https://www.cveoy.top/t/topic/nFmo 著作权归作者所有。请勿转载和采集!