动态链表的创建:前插法

代码如下:

#include <stdio.h>
#include<stdlib.h>
struct Student
{
   long num;
   float score;
   struct Student *next;
};
struct Student *creat()
{
	struct Student *head=NULL,*p=NULL;
	p=(struct Student *)malloc(sizeof(struct Student));
	scanf("%ld,%f",&p->num,&p->score);
	while(p->num!=0)
	{
		if(head==NULL)       //如果这是插入的第一个结点,此节点就是最后一个结点
		{
			p->next=NULL;    //那么它的next就指向空,即在其后没有结点了
			head=p;
		}
		else                 //如果不是,代表这不是插入的第一个结点,
                                  //即不是链表中最后一个结点
		{
			p->next=head;    //则使next指向head
			head=p;          //然后再让head为p的地址,从而相连
		}
		p=(struct Student *)malloc(sizeof(struct Student));
	    scanf("%ld,%f",&p->num,&p->score);   //这里是开辟一个新的动态空间,
                                                 //用来存放下一个结点
	}
	free(p);
	return head;
}
void print(struct Student *head)   
{
	struct Student *p;
	if(head==NULL)                //如果head为NULL,即为形成链表
	{
		printf("Empty!\n");     
		return;
	}
	p=head;                        //head为插入的最后一个结点,也是链表的第一个结点
	printf("Scores are:\n");
	if(p!=NULL)
	do
	{
		printf("num:%ld,score:%.2f\n",p->num,p->score);
		p=p->next;
	}while(p!=NULL);               //第一次插入的指针,也是链表的最后一个节点,其next指向为空
}
int main()
{
    struct Student *creat();                  
	void print(struct Student *head);
	struct Student *pt;
	pt=creat();
	print(pt);
	return 0;	
}

运行结果如下:

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值