链表的创建,输出,删除,插入操作。VS2012环境下可执行


需求:定义学生结构体,包含学号和得分两个属性。包含建立学生链表,输出链表,删除指定学号的学生,插入某个学生,这些操作。


定义结构体:

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

定义函数:createstu,del,insertstu,printstu。


具体实现:

#include <stdio.h>
#include <malloc.h>
#pragma warning(disable:4996)//

#define NULL 0

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

#define LEN sizeof(struct student)

int n;

struct student * create()
{
	struct student *head;
	struct student *p1;
	struct student *p2;
	n=0;
	p1=p2=(struct student *)malloc(LEN);
	scanf("%ld %f",&p1->num,&p1->score);
	head=NULL;
	while(p1->num!=0)
	{
		n++;
		if(n==1)head=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 printstu(struct student * head)
{
	struct student *p;
	p=head;
	if(p==NULL)printf("it is NULL!\n");
	while(p!=NULL)
	{
		printf("%ld,%5.1f\n",p->num,p->score);
		p=p->next;
	}
}

struct student *del(struct student * head,long num)
{
	struct student *pre,*p;

	pre=p=head;
	while((p->num!=num)&&(p!=NULL))
	{
		pre=p;p=p->next;
	}

	if(num==p->num)
	{
		if(p==head){ 
			head=p->next;
			free(pre);}
		else
		{
			pre->next=p->next;
			free(p);
			p=pre->next;
		}
		n--;
	}
	else printf("it is not been found\n");
	return head;
}

struct student *insertstu(struct student *head,struct student *stu)
{
	struct student *pre,*p;
	pre=p=head;
	while((p!=NULL)&&p->num<stu->num)
	{
		pre=p;p=p->next;
	}
	//insert it between pre and p
	if(p!=head)//insert the list 
	{
		stu->next=p;
		pre->next=stu;
	}
	else
	{
		stu->next=head;
		head=stu;
	}
	return head;
}
 void main(int argc,char *argv[])
{	
	struct student *head;
	struct student *stu;
	head = create();

	printstu(head);
	printf("\n delete the num 100:\n");
	head = del(head,100);
	printstu(head);
	printf("\n insert the num 100\n");
	stu=(struct student *)malloc(LEN);
	stu->num=100;
	stu->score=100;
	stu->next=NULL;

	head =insertstu(head,stu );
	printstu(head);

	printf("\n del the num 103:\n");
	head=del(head,103);
	printstu(head);
}



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值