#ifndef STACK_H
#define STACK_H
/*
* 定义栈元素类型结构
* */
struct stack_node {
void * data;
};
/*
* 定义栈元素节点类型
* */
typedef struct stack_node * snode;
/*
* 定义栈长度
* */
unsigned long stack_len;
/*
* 当前栈顶位置
* */
unsigned long stack_top;
/*
* 初始化栈
* 参数:栈最大长度
* 返回栈指针
* */
snode * init_stack(unsigned long len);
/*
* 入栈
* 参数1:栈指针
* 参数2:入栈数据指针
* */
void push_stack(snode * stack,snode val);
/*
* 出栈
* 参数:栈指针
* 返回出栈数据
* */
snode pop_stack(snode * stack);
/*
* 释放栈
* 参数:栈指针
* */
void free_stack(snode * stack);
#define STACK_H
/*
* 定义栈元素类型结构
* */
struct stack_node {
void * data;
};
/*
* 定义栈元素节点类型
* */
typedef struct stack_node * snode;
/*
* 定义栈长度
* */
unsigned long stack_len;
/*
* 当前栈顶位置
* */
unsigned long stack_top;
/*
* 初始化栈
* 参数:栈最大长度
* 返回栈指针
* */
snode * init_stack(unsigned long len);
/*
* 入栈
* 参数1:栈指针
* 参数2:入栈数据指针
* */
void push_stack(snode * stack,snode val);
/*
* 出栈
* 参数:栈指针
* 返回出栈数据
* */
snode pop_stack(snode * stack);
/*
* 释放栈
* 参数:栈指针
* */
void free_stack(snode * stack);
#endif
#include <stdio.h>
#include <stdlib.h>
#include "Stack.h"
snode * init_stack(unsigned long len){
if(0==len) return NULL;
stack_len=len;
stack_top=0;
snode * p=calloc(stack_len,sizeof(snode));
return p;
}
void push_stack(snode * stack,snode val){
if(stack_top>=stack_len){
return;
}
stack[stack_top]=val;
stack_top++;
}
snode pop_stack(snode * stack){
if(stack_top--==0){
stack_top=0;
}
snode r=stack[stack_top];
stack[stack_top]=NULL;
return r;
}
void free_stack(snode * stack){
if(NULL==stack) return;
int i;
for(i=0;i<stack_len;i++){
if(NULL!=stack[i]){
free(stack[i]);
}
}
free(stack);
}