链栈
#include<myhead.h>
typedef struct
{
int age;
int score;
char name[20];
}Students;
typedef struct node
{
Students data;
struct node *next;
}Node;
typedef struct
{
int len;
Node *top;
}Stack,*Pstack;
Pstack creat_stack()
{
Pstack p= malloc(sizeof(Stack));
if(p==NULL)
{
printf("创建失败");
}
p->len=0;
p->top=NULL;
return p;
}
int push_stack(Pstack L,Students 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 pop_stack(Pstack L)
{
if (L==NULL||L->len==0)
{
printf("栈不存在或为空\n");
return -1;
}
Node *Q=L->top;
printf("出栈节点:%s %d %d\n",Q->data.name,Q->data.age,Q->data.score);
L->top=Q->next;
L->len--;
free(Q);
Q=NULL;
printf("出栈成功\n");
return 0;
}
int out_put(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 %d %d\n",t->data.name,t->data.age,t->data.score);
t=t->next;
}
printf("\n");
return 0;
}
int main()
{
Students e[4]={{20,99,"张三"},{19,89,"李四"},{21,85,"王五"},{19,100,"刘六"}};
Pstack L=creat_stack();
for (int i = 0; i < 4; i++)
{
push_stack(L,e[i]);
}
out_put(L);
for (int i = 0; i < 4; i++)
{
pop_stack(L);
}
return 0;
}
链队列
#include<myhead.h>
typedef struct
{
int age;
int score;
char name[20];
}Students;
typedef struct node
{
Students data;
struct node *next;
}Node;
typedef struct
{
int len;
Node *rear;
Node *front;
}Queue,*Pqueue;
Pqueue get_head()
{
Pqueue p=malloc(sizeof(Queue));
if(p==NULL)
{
printf("创建失败");
return NULL;
}
p->front=0;
p->rear=0;
return p;
}
int in_queue(Pqueue L,Students e)
{
if (L==NULL)
{
printf("队列不存在\n");
return -1;
}
Node *p=malloc(sizeof(Node));
p->data=e;
if (L->rear==NULL)//当只有一个节点时
{
L->rear=p;
L->front=p;
}
else
{
L->rear->next=p;
L->rear=p;
}
L->len++;
printf("入队成功\n");
return 0;
}
int out_queue(Pqueue L)
{
if (L==NULL)
{
printf("队列不存在\n");
return -1;
}
Node *Q=L->front;
L->front=Q->next;
printf("出队节点是:%s %d %d\n",Q->data.name,Q->data.age,Q->data.score);
L->len--;
free(Q);
Q=NULL;
return 0;
}
int out_put(Pqueue L)
{
if (L==NULL||L->front==NULL)
{
printf("队列不存在\n");
return -1;
}
Node *t=L->front;
for (int i = 0; i < L->len; i++)
{
printf("%s %d %d\t",t->data.name,t->data.age,t->data.score);
t=t->next;
}
printf("\n");
return 0;
}
int main()
{
Students e[4]={{20,99,"张三"},{19,89,"李四"},{21,85,"王五"},{19,100,"刘六"}};
Pqueue L=get_head();
for (int i = 0; i < 4; i++)
{
in_queue(L,e[i]);
}
out_put(L);
for (int i = 0; i < 4; i++)
{
out_queue(L);
}
out_put(L);
return 0;
}