用c语言实现定义一个包含学生信息(学号,成绩)的链表,使其具有如下功能: (1) 逐个输入学生信息; (2) 逐个显示学生表中所有学生的相关信息; (3) 对数据表进行插入操作; (4) 对数据表进行删除操作。
时间: 2024-05-07 20:16:09 浏览: 100
1_lower7y7_定义一个包含学生信息(学号_成绩)的顺序表和链表(二选一)_姓名_使其具有如下功能_
5星 · 资源好评率100%
代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
struct student {
int num;
int score;
struct student *next;
};
struct student *create() {
struct student *head, *p, *q;
int num, score;
head = (struct student *)malloc(sizeof(struct student));
head->next = NULL;
q = head;
printf("Please input student's number and score (input -1 to quit):\n");
scanf("%d%d", &num, &score);
while (num != -1 && score != -1) {
p = (struct student *)malloc(sizeof(struct student));
p->num = num;
p->score = score;
p->next = NULL;
q->next = p;
q = p;
printf("Please input student's number and score (input -1 to quit):\n");
scanf("%d%d", &num, &score);
}
return head;
}
void display(struct student *head) {
struct student *p;
p = head->next;
printf("Number\tScore\n");
while (p != NULL) {
printf("%d\t%d\n", p->num, p->score);
p = p->next;
}
}
void insert(struct student *head) {
struct student *p, *q;
int num, score;
printf("Please input student's number and score to insert:\n");
scanf("%d%d", &num, &score);
p = (struct student *)malloc(sizeof(struct student));
p->num = num;
p->score = score;
p->next = NULL;
q = head;
while (q->next != NULL && q->next->num < num) {
q = q->next;
}
p->next = q->next;
q->next = p;
}
void delete(struct student *head) {
struct student *p, *q;
int num;
printf("Please input student's number to delete:\n");
scanf("%d", &num);
p = head;
while (p->next != NULL && p->next->num != num) {
p = p->next;
}
if (p->next == NULL) {
printf("Not found.\n");
} else {
q = p->next;
p->next = q->next;
free(q);
}
}
int main() {
struct student *head;
int choice;
head = create();
while (1) {
printf("Please choose an option:\n");
printf("1. Display all students.\n");
printf("2. Insert a student.\n");
printf("3. Delete a student.\n");
printf("4. Quit.\n");
scanf("%d", &choice);
switch (choice) {
case 1:
display(head);
break;
case 2:
insert(head);
break;
case 3:
delete(head);
break;
case 4:
exit(0);
default:
printf("Invalid choice.\n");
}
}
return 0;
}
```
这个程序中,我们定义了一个结构体 `student`,包含了学号和成绩两个信息,还有一个指向下一个学生结构体的指针。我们使用 `create()` 函数来创建一个链表,使用 `display()` 函数来显示所有学生的信息,使用 `insert()` 函数在链表中插入一个学生的信息,使用 `delete()` 函数在链表中删除一个学生的信息。最后,我们在 `main()` 函数中使用一个无限循环来让用户选择要执行的操作。当用户选择退出程序时,我们使用 `exit()` 函数来终止程序的运行。
阅读全文