//--------------------------------链表------------------------------
// 描述:通过动态分配内存实现链表
//------------------------------------------------------------------
//--------------------------------头文件----------------------------
// 描述:导入的头文件
//------------------------------------------------------------------
#include<iostream>
//--------------------------------命名空间--------------------------
// 描述:命名空间
//------------------------------------------------------------------
using namespace std;
//-----------------------------结构体-------------------------------
// 描述:定义结构体
//------------------------------------------------------------------
struct student {
char name[256];
int age;
int number;
student *next;
};
struct List {
student *head;
student *tail;
};
//-----------------------------函数--------------------------------
// 描述:全局函数定义
//-----------------------------------------------------------------
student *createStudent();
void addStudent(List &list);
void delStudent(List &list, int number);
void showStudent(List const list);
//--------------------------主函数------------------------------
//描述:主函数
//--------------------------------------------------------------
int main() {
int in;
int number = -1;
List list;
list.head = NULL;
list.tail = NULL;
do {
cout << "1:增加一个学生\n2:删除一个学生\n3:查看所有学生" << endl;
cin >> in;
switch (in)
{
case 1:
addStudent(list);
break;
case 2:
cout << "请输入要删除学生的学号:";
cin >> number;
delStudent(list, number);
break;
case 3:
showStudent(list);
break;
default:
break;
}
} while (in > 0);
return 0;
}
student *createStudent() {
student *s = new student;
cout << "请输入姓名:"; cin >> s->name;
cout << "请输入年龄:"; cin >> s->age;
cout << "请输入你的学号:"; cin >> s->number;
s->next = NULL;
return s;
}
void addStudent(List &list) {
if (list.head == NULL) {
//在链表头增加
student *s = createStudent();
list.head = s;
list.tail = s;
}
else {
//在链表尾增加
student *s = createStudent();
if (list.tail != NULL) {
list.tail->next = s;
list.tail = s;
}
else
list.tail = s;
}
}
void delStudent(List &list, int number) {
student *s = list.head;
student *s_last = NULL;
while (s != NULL) {
if (s->number == number) {
if (s_last != NULL) {
s_last->next = s->next;
}
else {
list.head = s->next;
}
if (list.tail = s) {
list.tail = NULL;
}
//删除这个学生
delete s;
cout << "删除学生成功" << endl;
return;
}
s_last = s;
s = s->next;
}
cout << "没有找到这个学生" << endl;
return;
}
void showStudent(List const list) {
student *s = list.head;
while (s != NULL) {
cout << "姓名:" << s->name << "-年龄:" << s->age << "学号:" << s->number << endl;
s = s->next;
}
}
C++的链表操作
最新推荐文章于 2024-08-14 15:16:06 发布