#include <stdio.h>
#include <stdlib.h>
typedef struct n{
int data;
struct n *next;
}stack;
stack *build()
{
stack *s=(stack *)malloc(sizeof(stack));
s->next=NULL;
s->data=NULL;
return s;
}
void *push(stack *s,int data) // 采用头插法来创建链式栈
{
stack *n=(stack *)malloc(sizeof(stack));
n->data=data;
if(s->next!=NULL)
{
n->next=s->next;
}else{
n->next=NULL;
}
s->next=n;
}
void Print(stack *s)
{
for(s=s->next;s;s=s->next)
{
printf("%d->",s->data);
}
printf("\n");
}
int pop(stack *s) //后进先出,弹出
{
if(s->next==NULL) //如果头指针的next为NULL,则栈为空
{
printf("the stack is empty!");
return;
}
stack *f=s->next;
int ret=f->data;
s->next=s->next->next;
free(f);
return ret;
}
int main()
{
stack *s=build();
push(s,111);
push(s,222);
push(s,333);
push(s,444);
Print(s);
int num=pop(s);
printf("%d\n",num);
num=pop(s);
printf("%d\n",num);
Print(s);
}