#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
/*栈是一个后入先出的容器*/
typedef struct Node{
struct Node * pnext;
int val;
}node ,*pnode;
typedef struct Stack{
pnode ptop;
pnode pbtom;
}stack,*pstack;
void gen_stack(pstack);//init stack
void push_stack(pstack p_stack, int val);//push stack
void show_stack(pstack p_stack);//print stack's val
void clear_stack(pstack p_stack);//clear and free stack element
void pop_stack(pstack p_stack,int * val_p);//pop stack top element
int main(void){
stack stack_r;
int pop_val;
pstack p_stack = &stack_r;
gen_stack(p_stack);
push_stack(p_stack, 1);
push_stack(p_stack, 2);
push_stack(p_stack, 3);
push_stack(p_stack, 4);
push_stack(p_stack, 5);
show_stack(p_stack);
printf("\n");
clear_stack(p_stack);
pop_stack(p_stack,&pop_val);
show_stack(p_stack);
push_stack(p_stack, 1);
push_stack(p_stack, 2);
push_stack(p_stack, 3);
push_stack(p_stack, 4);
push_stack(p_stack, 5);
show_stack(p_stack);
pop_stack(p_stack,&pop_val);
pop_stack(p_stack,&pop_val);
show_stack(p_stack);
printf("pop:%d\n",pop_val);
}
void gen_stack(pstack p_stack){
pnode p_node = (pnode)malloc(sizeof(node));
p_node->val = 0;
p_node->pnext = NULL;
p_stack->ptop = p_node;
p_stack->pbtom = p_node;
printf("gen_done\n");
}
void push_stack(pstack p_stack, int val_f){
pnode p_node = (pnode)malloc(sizeof(node));
p_node->val = val_f;
p_node->pnext = p_stack->ptop;
p_stack->ptop = p_node;
}
void show_stack(pstack p_stack){
if(p_stack->ptop == p_stack->pbtom){
printf("stack empty when show stack\n");
return;
}
pnode p_node;
p_node = p_stack->ptop;
while(p_node != p_stack->pbtom){
printf("%d\n",p_node->val);
p_node = p_node->pnext;
}
}
void clear_stack(pstack p_stack){
pnode p_node;
pnode p_node_p;
p_node = p_stack->ptop;
while(p_node != p_stack->pbtom){
p_node_p = p_node;
p_node = p_node->pnext;
p_node_p->val = 0;
p_node_p->pnext = NULL;
free(p_node_p);
p_stack->ptop = p_node;
}
}
void pop_stack(pstack p_stack,int * val_p){
if(p_stack->ptop == p_stack->pbtom){
printf("stack empty,can not pop\n");
return;
}
pnode p_node;
p_node = p_stack->ptop;
*val_p = p_node->val;
p_stack->ptop = p_node->pnext;
p_node->val = 0;
p_node->pnext = NULL;
free(p_node);
}
栈存储的简单实现例子
最新推荐文章于 2024-10-08 14:20:19 发布