#include <stdio.h>
#include <stdlib.h>
enum s
{
STACK_EMPTY,
STACK_NOEMPTY,
POP_NO,
POP_OK
};
struct node
{
int data;
struct node *next;
};
struct Stack
{
struct node *top; //栈顶
};
void init_Stack(struct Stack *s) //初始化链栈
{
s->top = NULL;
}
int empty_Stack(struct Stack *s) //判断栈空
{
if(s->top == NULL)
{
return STACK_EMPTY;
}
return STACK_NOEMPTY;
}
int PUSH_Stack(struct Stack *s,int num) //插入数据
{
struct node *p = (struct node*)malloc(sizeof(struct node));
if(p == NULL)
{
printf("malloc error!\n");
return -1;
}
p->data = num;
p->next = s->top;
s->top = p;
return 0;
}
int POP_Stack(struct Stack *s,int *num) //从栈顶删除数据
{
if(empty_Stack(s) == STACK_EMPTY)
{
return POP_NO;
}
struct node *p = s->top;
*num = p->data;
s->top = s->top->next;
free(p);
p = NULL;
return POP_OK;
}
int main()
{
struct Stack *s = (struct Stack*)malloc(sizeof(struct Stack));
int i = 0;
init_Stack(s);
for(i = 0;i < 5;i++)
{
PUSH_Stack(s,i+1);
}
int num = 0;
POP_Stack(s,&num);
printf("%d\n",num);
POP_Stack(s,&num);
printf("%d\n",num);
POP_Stack(s,&num);
printf("%d\n",num);
POP_Stack(s,&num);
printf("%d\n",num);
return 0;
}
关于链式栈的相关操作
最新推荐文章于 2021-03-19 22:22:42 发布