思维导图
链式栈
#include "link_stack.h"
//申请结点
node_p create_node(int data)
{
node_p new = (node_p)malloc(sizeof(node));
if(new==NULL)
{
printf("空间申请失败\n");
return NULL;
}
new->data = data;
return new;
}
//入栈
void push_stack(node_p *T,int data)
{
//不再需要入参为空的判断,因为T就在栈区
node_p new = create_node(data);
new->next = *T; //让新结点指向原来的栈顶元素
*T = new; //让栈顶指针指向新结点
}
//判空
int empty_stack(node_p T)
{
return T==NULL?1:0;
}
//出栈
void pop_stack(node_p *T)
{
node_p del = *T; //保存要释放的结点的首地址
*T =(*T)->next;
printf("要出栈的元素为%d\n",del->data);
free(del);
}
//输出栈
void show_stack(node_p T)
{
if(empty_stack(T))
{
printf("栈为空,无需输出\n");
return;
}
node_p p = T;
while(p!=NULL)
{
printf("%d->",p->data);
p=p->next;
}
printf("NULL\n");
}
顺序栈
#include "seq_stack.h"
//堆区申请顺序栈的空间
seq_p create_stack()
{
//堆区申请空间
seq_p S = (seq_p)malloc(sizeof(seq_stack));
//判断空间是否申请成功
if(S==NULL)
{
printf("空间申请失败\n");
return NULL;
}
//申请成功后,给data和top初始化
S->top = -1; //栈中没有元素时,让top指向-1位置
return S;
}
//入栈/压栈
void push_stack(seq_p S,datatype data)
{
//入参为空的判断
if(S==NULL)
{
printf("入参为空\n");
return;
}
//判满
if(full_stack(S))
{
printf("栈已满\n");
return;
}
//入栈
//先加再压,先自增top指针,再将数据压入栈
S->top++;
S->data[S->top]=data;
//S->data[++(S->top)]=data;
}
//输出栈
void show_stack(seq_p S)
{
if(S==NULL)
{
printf("入参为空\n");
return;
}
if(empty_stack(S))
{
printf("栈为空\n");
return;
}
//要求输出顺序和栈操作的顺序一致
for(int i=S->top;i>=0;i--)
{
printf("%-4d",S->data[i]);
}
putchar(10);
}
//判空
int empty_stack(seq_p S)
{
if(S==NULL)
{
printf("入参为空\n");
return -1;
}
return S->top==-1?1:0;
}
//判满
int full_stack(seq_p S)
{
if(S==NULL)
{
printf("入参为空\n");
return -1;
}
return S->top==MAX-1?1:0;
}
//出栈/弹栈
void pop_stack(seq_p S)
{
if(S==NULL)
{
printf("入参为空\n");
return;
}
if(empty_stack(S))
{
printf("栈为空\n");
return;
}
//出栈只需将top指针自减即可
//S->top--;
printf("出栈元素为%d\n",S->data[S->top--]);
}
//释放顺序栈
void free_stack(seq_p *S)
{
//入参为空的判断
if(S==NULL||*S==NULL)
{
printf("入参为空\n");
return;
}
free(*S);
*S=NULL;
}