写一个建立单链表的函数,设链表的表元素包含学号、姓名、一门课的成绩,写一个按照学号删除学生记录的函数;最后写一个主函数,先调用建立函数,输入待删除学生的学号,调用删除记录的函数,最后显示删除操作后的链表信息。
时间: 2023-02-24 18:12:18 浏览: 148
单链表的建立及增删改查等操作(学生信息)
5星 · 资源好评率100%
下面是用C语言实现的代码:
```
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int num;
char name[20];
int score;
struct Node *next;
};
struct Node *Create(void)
{
int n, i;
struct Node *head, *p, *q;
printf("请输入学生人数:");
scanf("%d", &n);
head = NULL;
for (i = 0; i < n; i++)
{
p = (struct Node *)malloc(sizeof(struct Node));
printf("请输入学号、姓名、成绩:");
scanf("%d%s%d", &p->num, p->name, &p->score);
p->next = NULL;
if (head == NULL)
{
head = p;
}
else
{
q->next = p;
}
q = p;
}
return head;
}
void Delete(struct Node *head, int num)
{
struct Node *p, *q;
p = head;
while (p != NULL && p->num != num)
{
q = p;
p = p->next;
}
if (p == NULL)
{
printf("该学生不存在!\n");
return;
}
if (p == head)
{
head = p->next;
}
else
{
q->next = p->next;
}
free(p);
}
void Print(struct Node *head)
{
struct Node *p;
p = head;
while (p != NULL)
{
printf("%d %s %d\n", p->num, p->name, p->score);
p = p->next;
}
}
int main()
{
int num;
struct Node *head;
head = Create();
printf("请输入要删除的学生学号:");
scanf("%d", &num);
Delete(head, num);
printf("删除操作后的链表信息:\n");
Print(head);
return 0;
}
```
阅读全文