链表的创建-详解

#include<iostream>
#include<queue>
#include<malloc.h>//建造空间malloc头
#include<stdio.h>
#include<string.h>
using namespace std;
struct student
{
	int a;
	student *next=NULL; //头指向空,初始化
};
int main()
{
	struct student *p1,*p2;//两个指针来创建
	int n;
	scanf("%d",&n);
	struct student *head;//定义个头来用来便于输出
	p2=head=(struct student *)malloc(sizeof(struct student));//p2建造个空间把p2指向头
	for(int i = 1; i <= n;i++)
	{
		p1=(struct student* )malloc(sizeof(struct student));//开辟创建空间
		scanf("%d",&p1->a);//定义值
		//printf("%d\n",p1->a);
		p1->next=NULL;//把其尾指针指向空
		p2->next=p1;//让前一个的尾部指向这一个创建的
		p2=p2->next;//迁移前一个到刚创建的
	}
	p1->next=NULL;//把尾指针指向空
	struct student *p = head->next;//定义个输出指针
	while(p != NULL)//当指针为空不在输出
	{
		printf("%d\n",p->a);
		p=p->next;//移到下一个
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_43568078/article/details/85111131