[作业]链表实现

#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");
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值