码迷,mamicode.com
首页 > 编程语言 > 详细

C语言——链表

时间:2014-12-07 00:10:52      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:c语言   链表   指针   struct   

//链表的操作
#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语言——链表

标签:c语言   链表   指针   struct   

原文地址:http://blog.csdn.net/williamfan21c/article/details/41781201

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!