用c++编写:将学生链表的创建,插入,删除操作分别写入对应的函数中。 创建:Begin_CreatLink() 插入:Begin_AddNew() 删除:Begin_Delete()
时间: 2024-05-03 07:21:57 浏览: 26
假设学生节点的结构体为:
```
typedef struct StudentNode {
int id; // 学号
char name[20]; // 姓名
int age; // 年龄
struct StudentNode *next; // 下一个节点指针
} StudentNode;
```
创建链表函数:
```
StudentNode* Begin_CreatLink() {
StudentNode *head = NULL, *p = NULL, *tail = NULL;
int n = 0;
printf("请输入学生人数:");
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
p = (StudentNode*)malloc(sizeof(StudentNode));
printf("请输入第%d个学生的信息:\n", i);
printf("学号:");
scanf("%d", &(p->id));
printf("姓名:");
scanf("%s", p->name);
printf("年龄:");
scanf("%d", &(p->age));
p->next = NULL;
if (head == NULL) {
head = p;
tail = p;
} else {
tail->next = p;
tail = p;
}
}
return head;
}
```
插入节点函数:
```
void Begin_AddNew(StudentNode *head) {
int id;
StudentNode *p = head;
printf("请输入要插入的学生学号:");
scanf("%d", &id);
while (p != NULL) {
if (p->id == id) {
StudentNode *newNode = (StudentNode*)malloc(sizeof(StudentNode));
printf("请输入要插入的学生信息:\n");
printf("学号:");
scanf("%d", &(newNode->id));
printf("姓名:");
scanf("%s", newNode->name);
printf("年龄:");
scanf("%d", &(newNode->age));
newNode->next = p->next;
p->next = newNode;
printf("插入成功!\n");
return;
}
p = p->next;
}
printf("未找到该学生,插入失败!\n");
}
```
删除节点函数:
```
void Begin_Delete(StudentNode *head) {
int id;
StudentNode *p = head, *pre = NULL;
printf("请输入要删除的学生学号:");
scanf("%d", &id);
while (p != NULL) {
if (p->id == id) {
if (pre == NULL) {
head = p->next;
} else {
pre->next = p->next;
}
free(p);
printf("删除成功!\n");
return;
}
pre = p;
p = p->next;
}
printf("未找到该学生,删除失败!\n");
}
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)