顺序栈
#include "seq_stack.h"
//初始化
seq_p create_stack()
{
seq_p s = (seq_p)malloc(sizeof(seq_stack));
if(s==NULL){
printf("s is NULL\n");
return NULL;
}
s->top = -1;
return s;
}
//判空
int empty_stack(seq_p s)
{
if(s==NULL){
printf("s is NULL\n");
return -1;
}
return s->top==-1?1:0;
}
//判满
int full_stack(seq_p s)
{
if(s==NULL){
printf("s is NULL\n");
return -1;
}
return s->top==MAX-1?1:0;
}
//入栈/压栈
void push_stack(seq_p s,datatype data)
{
if(s==NULL){
printf("s is NULL\n");
return;
}
if(full_stack(s)){
printf("seq_stack is full\n");
return;
}
s->data[++s->top] = data;
}
//出栈/弹栈
datatype pop_stack(seq_p s)
{
if(s==NULL){
printf("s is NULL\n");
return -1;
}
if(empty_stack(s)){
printf("seq_stack is empty\n");
return -2;
}
return s->data[s->top--];
}
//从栈顶到栈底依次输出栈中元素
void show_stack(seq_p s)
{
int i;
if(s==NULL){
printf("s is NULL\n");
return;
}
if(empty_stack(s)){
printf("seq_stack is empty\n");
return;
}
printf("seq_stack data from top to bottom:");
for(i=s->top;i>-1;i--){
printf("%-4d",s->data[i]);
}
putchar(10);
}
//释放顺序栈
void free_stack(seq_p *p)
{
if(p==NULL || *p==NULL){
printf("p or *p is NULL\n");
return;
}
free(*p);
*p=NULL;
}
链式栈
#include "link_stack.h"
//创建新结点
node_p create_node(int data)
{
node_p new = (node_p)malloc(sizeof(node));
if(new==NULL){
printf("new is NULL\n");
return NULL;
}
new->data = data;
return new;
}
//判空
int empty_link(node_p t)
{
return t==NULL?1:0;
}
//入栈
void push_link(node_p *t,int data)
{
//不需要进行入参检测,因为t本身就在栈区
node_p new = create_node(data);
new->next = *t;
*t = new;
}
//出栈
void pop_link(node_p *t)
{
if(empty_link(*t)){
printf("link_stack is empty\n");
return;
}
node_p p = *t;
*t = p->next;
printf("pop element:%d\n",p->data);
free(p);
}
//输出
void show_link(node_p t)
{
if(empty_link(t)){
printf("link_stack is empty\n");
return;
}
node_p p = t;
while(p!=NULL){
printf("%d->",p->data);
p = p->next;
}
puts("NULL");
}