综合本章例9.9(建立链表的函数creat)、例9.10(输出链表的函数print)和本章习题 第7题(删除链表中结点的函数del)、第8题(插入结点的函数insert),再编写一个主函数, 先后调用

/*综合本章例9.9(建立链表的函数creat)、例9.10(输出链表的函数print)和本章习题
第7题(删除链表中结点的函数del)、第8题(插入结点的函数insert),再编写一个主函数,
先后调用这些函数。用以上五个函数组成一个函数,实现链表的建立、输出、删除和插入,
在主函数中指定需要删除和插入的结点的数据*/

#include <stdio.h>
#include <stdlib.h>
#define LEN sizeof(struct Student)

struct Student{
	long num;
	float score;
	struct Student *next;
}; 

int n;

//创建链表 
struct Student *creat(struct Student *head)
{
	struct Student *p1,*p2;
	n = 0;
	p1 = p2 = (struct Student *)malloc(LEN);
	scanf("%ld,%f",&p1->num,&p1->score);
	while(p1->num != 0)
	{
		n = n + 1;
		if(n == 1)head->next = p1;
		else p2->next = p1;
		p2 = p1;
		p1 = (struct Student *)malloc(LEN);
		scanf("%ld,%f",&p1->num,&p1->score);
	}
	p2->next = NULL;
	return (head);
}

//输出链表 
void print(struct Student *head)
{
	struct Student *p;
	printf("\nNow,These %d records are:\n",n);
	p = head->next;
	if(head != NULL)
	{
		do
		{
			printf("%ld %5.1lf\n",p->num,p->score);
			p = p->next;
		}while(p != NULL);
	}
}

//删除某个学生的信息 
void del(struct Student *head,long a)
{
	struct Student *p,*q;
	p = q = head;
	int flag = 0;
	
	while(p)
	{
		if(head->num == a)
		{
			q = head->next;
			head = q;
		}
		if(p->num == a)
		{
			while(q->next != p)
			q = q->next;
			
			q->next = p->next;
			flag = 1;
		}
		p = p->next;	
	}
	
	if(flag == 0)
	{
		printf("no find!\n");
	}
	else
	{
		printf("succeed!");
		n = n - 1;
	}
	
} 

//插入结点 
void insert(struct Student *head,struct Student *p,int site)
{
	struct Student *q;
	q = head;
	int flag = 0,m;
	
	if(site >= 1) 
	{	
	    //找到插入位置的前一个结点 
		for(m = 1;m < site;m++)
	    {
		    q = q->next;
	    }
	    //开始插入
	    p->next = q->next;
        q->next = p;
		
        flag = 1;   
	}
	
	if(flag == 0)
	{
		printf("no find!\n");
	}
	else
	{
		printf("succeed!");
		n = n + 1; 
	}
	
} 

int main()
{
	struct Student *head;
	long a;
	struct Student *p;
	int site;
	
	head = (struct Student *)malloc(LEN);
	head->num = 0;
	head->score = 0;
	head->next = NULL;
	creat(head);
	print(head);
	
	printf("please enter the student's student number to delete:");
	scanf("%ld",&a);
	del(head,a);
	print(head);
		
	printf("please enter the student's data to insert:");
	p = (struct Student *)malloc(LEN);
	scanf("%ld,%f",&p->num,&p->score);
	printf("please enter the loction to insert:");
	scanf("%d",&site);
	insert(head,p,site);
	print(head);
 } 

谭浩强C程序设计(第四版)p330第9题
我为链表加了一个头结点,这样进行删除和插入操作方便点。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值