|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
struct student //构建结构体
{ char name[20];
struct student * pnext;
};
void buildstu(struct student*p,int n);
void print(struct student*p,int n);
int main() //主函数
{
int n;
puts("please input how many students:\nnum = ");
scanf("%d",&n); //链表的个数
struct student * phead=(struct student *)malloc(sizeof(struct student));
buildstu(phead,n); //构建链表
print(phead,n); //输出
return 0;
}
void buildstu(struct student*p,int n) //构建链表函数
{
struct student* ptail=p; //就是此处不明白,p内的指针,一直也没赋值,但是居然指向的是首节点
for(int i=0;i<n;i++) //下面只对ptail赋值,p应该一直就是个随机值才对
{
struct student *pnew=(struct student *)malloc(sizeof(struct student));
if(pnew==NULL)
{ puts("Allocation failure!!!"); exit(-1); }
ptail->pnext=pnew;
scanf("%s",pnew->name);
ptail=pnew;
}
}
void print(struct student*p,int n) //输出函数
{
struct student* ptail=p->pnext;
for(int i=0;i<n;i++)
{
printf("%s\n",ptail->name);
ptail=(ptail->pnext);
}
}
|
|