无头结点链表操作

  • 第一种思路

定义结构体类型

struct student
{
	int num;
	int score;
	struct student *next;
};

创建链表

struct student *creat(int n)
{
	int i;
	struct student *head=NULL;
	struct student *p1,*p2=NULL;
	
	for(i=1;i<=n;i++)
	{
		if((p1=(struct student *)malloc(LEN))==NULL)
		{
			printf("不能成功分配粗储存块!");
			exit(0);
		}
		p1->next=NULL;
		scanf("%d%d",&p1->num,&p1->score);
		if(i==1) head=p1;
		else p2->next=p1;
		p2=p1;
	}
	p2->next=NULL;
	return head;
}

往链表中插入结点的函数

struct student *insert(struct student *head,struct student *inse)
{
	struct student *p0,*p1,*p2;
	p1=head; p0=inse;

	if(head==NULL)
	{
		head=p0; p0->next=NULL;
	}
	while((p0->num>p1->num)&&(p1->next!=NULL))
	{
		p2=p1; p1=p1->next;
	}
	if(head==p1){
		p0->next=head;
		head=p0;
	}
	else if(p0->num>p1->num){
		p1->next=p0; p0->next=NULL;
	}
	else{
		p2->next=p0;
		p0->next=p1;
	}
	return(head);
}

删除链表中结点的函数

struct student *delete_node(struct student *head,int num)
{
	struct student *p1=head, *p2=head;

	while((p1->num!=num)&&(p1->next!=NULL))
	{
		p2=p1; p1=p1->next;
	}

	if(p1->num==num)
	{
		if(p1==head) head=p1->next;
		else p2->next=p1->next;
		free(p1);
	}
	else printf("无删除结点!");

	return head;	
}

main函数

int main()
{
	struct student inse;
	struct student *head,*p;
	int i,num;

	// 输出原链表
	head=creat(4);
	p=head;
	for(i=1;i<=4;i++)
	{
		printf("%d%d\n",p->num,p->score);
		p=p->next;
	}

	// 插入学生结点后的链表
	printf("\n请输入插入学生信息:");
	scanf("%d%d",&inse.num,&inse.score);
	p=insert(head,&inse);
	for(i=1;i<=5;i++)
		{
			printf("%d  %d\n",p->num,p->score);
			p=p->next;
		}

	// 删除结点后的链表
	printf("输入要删除的学生学号:");
	scanf("%d",&num);
	p=delete_node(head,num);
	for(i=1;i<=4;i++)
		{
			printf("%d  %d\n",p->num,p->score);
			p=p->next;
		}

	return 0;
}

  • 第二种思路(红本)

int n;// 全局变量

创建链表

struct student *creat()
{
	struct student *head=NULL;
	struct student *p1,*p2;
	n=0;

	p1=p2=(struct student *)malloc(LEN);
	scanf("%d%d",&p1->num,&p1->score);
	while(p1->num)
	{
		n=n+1;
		if(n==1) head=p1;
		else p2->next=p1;
		p2=p1;
		p1=(struct student *)malloc(LEN);
		scanf("%d%d",&p1->num,&p1->score);
	}
	p2->next=NULL;
	return(head);
}

猜你喜欢

转载自blog.csdn.net/weixin_44427114/article/details/102150889