C语言单向链表的新建以及遍历输出

#include <stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct play{
	int id;
	char name[20];
	struct play *next;
}PLAY;
//创建链表
PLAY * build(int num){
	PLAY *head,*playnew,*playend;
	head=(PLAY *)malloc(sizeof(PLAY));//头结点分配空间
	if (head == NULL)
	{
		return NULL;
	}
	playend=head;//playend始终指向尾结点
	playnew=NULL;
	int i;
	for(i=0;i<num;i++){
		playnew=(PLAY *)malloc(sizeof(PLAY));
		printf("请输入玩家编号:");
		scanf("%d",&playnew->id);
		printf("请输入玩家姓名:");
		scanf("%s",&playnew->name);
		playend->next=playnew;//此时的playend就是head,将head头结点与新节点playnew相连
		playnew->next=NULL;//使playnew节点为尾结点,使尾节点的下一内存地址为null	
		playend=playnew;//使playend成为尾结点
		playend->next=NULL;//使尾节点的下一内存地址为null			
	}
	return head;
}
//链表遍历
printinto(PLAY *play,int num){
	play=play->next;//取出第一个有效节点(即头结点的next)
	int i;
	for(i=0;i<num;i++){
		printf("玩家编号为:%d\n",play->id);
		printf("玩家名称为:%s\n",play->name);
		play=play->next;//当前节点往下移动一位,playr指向下一个有效节点
	} 
}
int main(){
	PLAY *head;
	head=NULL;
	int num=3;
	head=build(num);
	printinto(head,num);
	return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值