栈存储的简单实现例子

#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);
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值