作业:链栈,自己实现一遍,但是节点存储不是整数,存储学生信息(年龄,分数,姓名)三级引用。
1、建立学生信息结构体,将data改为学生信息结构体类型。
2、循环入栈和入队。
#include<myhead.h>
#define MAX 5
typedef struct students
{
char name[20];
int age;
int score;
}stu;
typedef struct node
{
stu data;
struct node *next;
}Node;
typedef struct
{
int len;
Node *top;
}Stack,*Pstack;
Pstack create_stack()
{
Pstack p=malloc(sizeof(Stack));
if(p==NULL)
{
printf("创建链栈失败!\n");
return NULL;
}
p->len=0;
p->top=NULL;
return p;
}
int push_stack(Pstack L,stu e)
{
if(L==NULL)
{
printf("链表不存在!\n");
return -1;
}
Node *p=malloc(sizeof(Node));
p->data=e;
p->next=L->top;
L->top=p;
L->len++;
printf("入栈成功!\n");
return 0;
}
int output_stack(Pstack L)
{
if(L==NULL||L->len==0)
{
printf("链表为空!\n");
return -1;
}
Node *t=L->top;
for(int i=0;i<L->len;i++)
{
printf("姓名:%s\t",t->data.name);
printf("年龄:%d\t",t->data.age);
printf("分数:%d\n",t->data.score);
t=t->next;
}
printf("\n");
return 0;
}
int main(int argc, char const *argv[])
{
stu e[MAX];
printf("请输入学生信息:\n");
for(int i=0;i<MAX;i++)
{
printf("姓名:");
scanf("%s",e[i].name);
printf("年龄:");
scanf("%d",&e[i].age);
printf("分数:");
scanf("%d",&e[i].score);
}
Pstack L=create_stack();
for(int i=0;i<MAX;i++)
{
push_stack(L,e[i]);
}
output_stack(L);
return 0;
}