#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define len sizeof(struct stu)
typedef struct stu *node;
#define null NULL
struct stu {
int id;
int degree;
char name[100];
struct stu *next;
};
node make() {
node p = malloc(len);
if (p) {
p->next = null;
return p;
}
}
node del(node head) {
int i;
printf("请输入学号");
scanf("%d", &i);
node p = head;
node q = null; //用俩个指针不停向后移动,一个指向前一个,一个指向后一个
for (; p; q = p, p = p->next) {
if (p->id == i) {
if (q) {
q -> next = p->next; //将q的下一个变为p的下一个,就是跳过了p这个
free(p);
return head;
}
//其实有要删除的数据刚好是第一个的这种情况,但我头节点没存就没管了
//实际上应该要考虑下的
p = q->next;
free(q);
return p;
//还是写出来吧,但确实不用考虑这个情况
}
}
printf("该学生不存在\n");
return head;
}
node find(node head) {
int i;
printf("请输入学号");
scanf("%d", &i);
for (node p = head; p; p = p->next) {
if (p->id == i) {
printf("%d\t%d\t%s\n", p->id, p->degree, p->name);
return head;
}
}
printf("no this student\n");
return head;
}
node insert(node head) {
node p = make();
int b, c;
char st[30] ;
printf("插入学生学号:");
scanf("%d", &b);
printf("插入学生姓名:");
scanf("%s", st);
printf("插入学生成绩:");
scanf("%d", &c);
p->id = b;
strcpy(p->name, st); /*给数组赋字符串*/
p->degree = c;
if (p) {
p->next = head ->next;
head->next = p;
}
//从头部插入
return head;
}
node read(node head) {
if (head == null) {
printf("无人\n");
return head;
}
printf("学生学号\t学生姓名\t学生成绩\n");
for (node p = head ; p; p = p->next) {
printf(" %d\t\t %s\t\t %d\n", p->id, p->name, p->degree);
}
}
int main() {
node head = make();
head->id = -1;
head->degree = -1;
//头节点不存数据,随便赋的值
while (1) {
int flag;
printf("1.查看\n2.查找\n3.插入\n4.删除\n5.退出\n");
printf("输入操作\n");
scanf("%d", &flag);
switch (flag) {
case 1:
read(head->next);//由于头部没存数据,所以从head—>next开始
break;
case 2:
find(head);
break;
case 3:
insert(head);
break;
case 4:
del(head);
break;
case 5:
return 0;
}
system("pause");
system("cls");
}
}
[作业]链表实现
最新推荐文章于 2024-07-08 21:10:38 发布