建立一个链表,链表节点用于存储如下结构体: struct Student { long num; //学号 char name[20]; //姓名 char sex; //性别 float score; //成绩 }; 要求:使用函数和指针进行合理的编程, 建立链表 struct SLink { struct Student s; struct SLink *next; } *np; ,并设计如下函数: 1)createLink()生成一个空链表; 2)insertData(struct Student s)按学生学号由小到大的顺序,将s插入到链表合适的位置; 提示:使用np=(struct SLink *) malloc(sizeof(struct SLink)开辟内存以建立新节点。 3)deleteData(long num)删除学号为num的节点。 提示:使用free(np)释放被删除节点的内存; 4)printLink()顺序打印输出链表各节点的内容。
时间: 2023-04-08 19:01:33 浏览: 114
我可以回答这个问题。以下是建立链表并设计相应函数的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Student {
long num; //学号
char name[20]; //姓名
char sex; //性别
float score; //成绩
};
struct SLink {
struct Student s;
struct SLink *next;
} *head, *tail;
void createLink() {
head = tail = NULL;
}
void insertData(struct Student s) {
struct SLink *p, *q, *np;
np = (struct SLink *) malloc(sizeof(struct SLink));
np->s = s;
np->next = NULL;
if (head == NULL) {
head = tail = np;
} else {
p = head;
while (p != NULL && p->s.num < s.num) {
q = p;
p = p->next;
}
if (p == head) {
np->next = head;
head = np;
} else if (p == NULL) {
tail->next = np;
tail = np;
} else {
q->next = np;
np->next = p;
}
}
}
void deleteData(long num) {
struct SLink *p, *q;
p = head;
while (p != NULL && p->s.num != num) {
q = p;
p = p->next;
}
if (p == NULL) {
printf("学号为%ld的学生不存在!\n", num);
} else {
if (p == head) {
head = head->next;
} else if (p == tail) {
tail = q;
tail->next = NULL;
} else {
q->next = p->next;
}
free(p);
printf("学号为%ld的学生已删除!\n", num);
}
}
void printLink() {
struct SLink *p;
p = head;
while (p != NULL) {
printf("学号:%ld,姓名:%s,性别:%c,成绩:%.2f\n", p->s.num, p->s.name, p->s.sex, p->s.score);
p = p->next;
}
}
int main() {
struct Student s1 = {1001, "张三", 'M', 85.5};
struct Student s2 = {1003, "李四", 'F', 92.0};
struct Student s3 = {1002, "王五", 'M', 78.5};
createLink();
insertData(s1);
insertData(s2);
insertData(s3);
printf("插入三个学生后,链表内容为:\n");
printLink();
deleteData(1003);
printf("删除学号为1003的学生后,链表内容为:\n");
printLink();
return 0;
}