首页 > 代码库 > C语言——链表

C语言——链表

//链表的操作
#include<stdio.h>
#include<malloc.h>
#define NULL 0  
#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;
	head=NULL;
	p1=p2=(struct student*)malloc(LEN);//分配存储空间
	printf("input num,score:\n");
	scanf("%ld,%f",&p1->num,&p1->score);
	while(p1->num!=0)
	{
		n=n+1;
		if(n==1)//第一个结点
			head=p1;
		else
		{
			p2->next=p1;
			p2=p1;
		}
		p1=(struct student*)malloc(LEN);
		printf("input num&&score:\n");
		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;
	if(head!=NULL)
		while(p!=NULL)
		{
			printf("%ld\t%5.2f\n",p->num,p->score);
			p=p->next;
		}
}
struct student *del(struct student *head,long num)//链表的删除操作
{
	struct student *p1,*p2;
	if(head==NULL)//空链表
	{
		printf("\nListLink is null\n");
		goto end;
	}
	p1=head;
	while(num!=p1->num&&p1->next!=NULL)//查找要删除的结点,p1指向要删除的结点,p2指向要删除的结点的前一个结点
	{
		p2=p1;
		p1=p1->next;
	}
	if(num==p1->num)
	{
		if(p1==head)//要删除的结点是第一个结点
			head=p1->next;
		else
			p2->next=p1->next;
		printf("delete %ld is succeed\n",num);
		n=n-1;
	}
	else
		printf("%ld not been found!\n",num);
end:
	return head;
}
struct student *insert(struct student *head,struct student *stud)//链表的插入操作
{
	struct student *p0,*p1,*p2;//p1存放插入位置的后一个结点,p2存放插入位置的前一个结点
	p1=head;
	p0=stud;//要插入的结点
	if(head==NULL)//若链表为空链表
	{
		head=p0;
		p0->next=NULL;
	}
	else
	{
		while((p0->num>p1->num)&&(p1->next!=NULL))//查找要插入的位置
		{
			p2=p1;
			p1=p1->next;
		}
		if(p0->num<=p1->num)
		{
			if(head==p1)//插入位置为第一个结点,表头
				head=p0;
			else
				p2->next=p0;
			p0->next=p1;
		}
		else
		{
			p1->next=p0;//插入位置为表尾,
			p0->next=NULL;
		}
	}
	n=n+1;
	return head;
}
void main()
{
	struct student *head,*stu;
	long del_num;
	printf("input records:\n");
	head=creat();//创建链表
	print(head);

	printf("\ninput the delete number:");
	scanf("%ld",&del_num);
	while(del_num!=0)//删除结点
	{
		head=del(head,del_num);
		print(head);
		printf("\ninput the delete number:");
		scanf("%ld",&del_num);
	}
	printf("\ninput insert record:");
	stu=(struct student*)malloc(LEN);
	scanf("%ld,%f",&stu->num,&stu->score);
	while(stu->num!=0)//插入结点
	{
		head=insert(head,stu);
		print(head);
		printf("\ninput insert record:");
		stu=(struct student*)malloc(LEN);
		scanf("%ld,%f",&stu->num,&stu->score);
	}
}

C语言——链表