链栈,自己实现一遍,但是节点存储不是整数,存储学生信息(年龄,分数,姓名)三级引用。
1、建立学生信息结构体,将data改为学生信息结构体类型。
2、循环入栈和出栈。
#include <myhead.h>
typedef struct student
{
int age;
float score;
char name[20];
}stu;
typedef struct node
{
stu s;
struct node *next;
}no,*Pnode;
typedef struct
{
Pnode top;
Pnode next;
}Stact,*Pstact;
Pstact create()
{
Pstact p=malloc(sizeof(Stact));
if(p==NULL)
{
printf("初始化失败\n");
return NULL;
}
p->top=NULL;
p->next=NULL;
printf("初始化成功\n");
return p;
}
int intput(Pstact Q)
{
if(Q==NULL)
{
printf("入栈失败\n");
return -1;
}
else
{
int n;
printf("输入学生信息个数:");
scanf("%d",&n);
printf("\tage\tscore\tname\n");
for(int i=0;i<n;i++)
{
Pnode p=malloc(sizeof(no));
printf("请输入第%d个学生的信息:\n",i+1);
printf("age:");
scanf("%d",&p->s.age);
printf("score:");
scanf("%f",&p->s.score);
printf("name:");
scanf("%s",p->s.name);
p->next=Q->next;
Q->next=p;
Q->top=p;
printf("录入成功\n");
}
return 0;
}
}
int pop(Pstact Q)
{
if(Q==NULL||Q->top==NULL)
{
printf("出栈失败\n");
return -1;
}
while(Q->top!=NULL)
{
printf("出栈数据为:\n");
printf("\tage\tscore\tname\n");
printf("\t%d\t%.2f\t%s\n",Q->top->s.age,Q->top->s.score,Q->top->s.name);
Pnode L=Q->top;
Q->top=L->next;
Q->next=L->next;
free(L);
L=NULL;
}
}
int main(int argc, const char *argv[])
{
Pstact Q=create();
intput(Q);
pop(Q);
return 0;
}
代码运行效果
标签:存储,return,int,top,next,链栈,printf,NULL,三级 From: https://blog.csdn.net/m0_72110718/article/details/143438367