作业八 链表

作业八 链表综合运用

https://github.com/q1263868407/linkyunyong 第一次尝试上传github

这次尝试用头文件来给函数分类

八、案例 7:综合教材第 9 章例 9.9、例 9.10 和习题第 7 题、第 8 题, 再编写一个主函数,先后调用这些函数。用以上 5 个函数组成一个程 序,实现链表的建立、输出、删除和插入。在主函数中指定需要删除 和插入的结点。

creat.h

#define LEN sizeof(struct Student)
struct Student
{
	long num;
	float score;
	struct Student* next;
};
int n;
struct Student* creat(void)
{
	struct Student* head;
	struct Student* p1, * p2;
	n = 0;
	p1 = p2 = (struct Student*)malloc(LEN);
	scanf_s("%ld,%f", &p1->num, &p1->score);
	head = NULL;
	while (p1->num != 0)
	{
		n = n + 1;
		if (n == 1)head = p1;//如果n=1 则p1此时是第一个节点 另头结点=p1
		else p2->next = p1;//如果n!=1则p1此时是第n个学生的节点 
		p2 = p1;
		p1 = (struct Student*)malloc(LEN);
		scanf_s("%ld,%f", &p1->num, &p1->score);
	 }
	p2->next = NULL;
	return(head);
}

delint.h

void del(struct Student *head,int n) //0是链表第一位
{
	int cnt = 1;
	struct Student* p, *q;
	p = head;
	while (p->next && cnt < n)
	{
		p = p->next;
		cnt++;
	}
	if (!(p->next))//p->next是要删除的节点
		return 0;
	q = p->next;//此时q为被删除节点本身,p为被删除节点前一个节点
	p->next = q->next;//将被删除的节点前一个节点指针域指向后一个节点
	free(q);
	return 1;
}

void insert(struct Student* head, int n,int s,int num)//0是链表第一位
{
	struct Student* p, * q;
	int cnt = 1;
	p = head;
	while (p && cnt < n)
	{
		cnt++;
		p = p->next;
	}
	if (!p)
		return 0;
	q = (struct Student*)malloc(sizeof(LEN));//初始化要开辟的节点q
	q->num = s;//为q赋值
	q->score = num;
	q->next = p->next;//另q的指针域指向P的下一个节点,因为q插在p和下一个节点之间
	p->next = q;
}

output.h

void print(struct Student* head)
{
	struct Student* p;
	p = head;
	if(head!=0)
		do
		{
			printf("%ld %5.1lf\n", p->num, p->score);
			p = p->next;
		} while (p != 0);
}

main.c

#include<stdio.h>
#include<stdlib.h>
#include"creat.h"
#include"output.h"
#include"delint.h"
int main()
{
	struct Student *a;
	a = creat();
	print(a);
	del(a, 1);
	insert(a, 1,1,50);
}
posted @ 2022-05-13 11:49  孟夏十二  阅读(52)  评论(0编辑  收藏  举报