栈
1、栈的创建
#define MAX 5
typedef int data_type;
typedef struct{
data_type buf[MAX];
int top;
}stack;
stack *create_stack(){
stack *s=(stack *)malloc(sizeof(stack));
if(NULL==s){
printf("malloc fail!\n");
return NULL;
}
memset(s,0,sizeof(stack));
s->top=-1;
return s;
}
2、入栈
void push(stack *s,data_type data){
if(is_full(s)){
return;
}
s->buf[++s->top]=data;
}
3、出栈
data_type pop(stack *s){
return s->buf[s->top--];
}
4、判断空栈
int is_empty(stack *s){
return s->top==-1?1:0;
}
5、判断满栈
int is_full(stack *s){
return s->top==MAX-1?1:0;
}
6、获得栈顶元素的值
data_type get_top(stack *s){
return s->buf[s->top];
}
链栈
栈头指向栈内的第一个元素
1、链栈的创建
typedef int data_type;
typedef struct node{
data_type data;
struct node *next;
}link_node;
//栈头
typedef struct{
link_node *top;
int n;
}stack_top;
stack_top *create_link_stack(){
stack_top *top=NULL;
top=(stack_top *)malloc(sizeof(stack_top));
if(NULL==top){
printf("malloc fail\n");
return NULL;
}
memset(top,0,sizeof(stack_top));
return top;
}
2、入栈
void push(stack_top *s,data_type data){
link_node *node=(link_node *)malloc(sizeof(link_node));
if(NULL==node){
printf("malloc fail!");return;
}
node->data=data;
node->next=s->top;
s->top=node;
s->n++;
}
3、出栈
data_type pop(stack_top *s){
link_node *temp=NULL;
data_type result;
temp=s->top;
result=temp->data;
s->top=temp->next;
free(temp);
temp=NULL;
s->n--;
return result;
}
4、判断栈空
int is_empty(stack_top *s){
return s->top==NULL?1:0;
}