线性结构的两种常见应用之一
栈
定义:一种可以实现先进后出的存储结构
栈类似于箱子,堆放在箱子里的书先进后出
分类:静态栈
动态栈
算法:出栈
压栈
应用:
函数调用
中断
表达式求值
内存分配
缓冲处理
迷宫
栈程序的演示
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
typedef struct node{
int data;
struct node*pnext;
}node,*pnode;
typedef struct stack{
pnode ptop;
pnode pbottom;
}stack,*pstack;
void init(pstack ps);
void push(pstack ps,int val);
void traverse(pstack ps);
void clear(pstack ps);
bool pop(pstack ps,int*pval);
int main(void){
stack s;//等价于struct stack s
int val;
init(&s);//目的是造出一个空栈
push(&s,1);//压栈
push(&s,2);
push(&s,3);
push(&s,4);
push(&s,5);
push(&s,6);
//traverse(&s);//遍历
//clear(&s);
traverse(&s);
if(pop(&s,&val))
printf("出栈成功!出栈的元素是:%d\n",val);
else
printf("出栈失败!\n");
return 0;
}
栈的初始化
创建一个空栈
![](https://i-blog.csdnimg.cn/blog_migrate/a908931faa8f5bd5c4cfcf3880f602ad.png)
![](https://i-blog.csdnimg.cn/blog_migrate/ab1119c1fda467e83a542ce2b40c0117.png)
void init(pstack ps){
ps->ptop=(pnode)malloc(sizeof(node));
if(NULL==ps->ptop)
{
printf("内存分配失败!\n");
exit(-1);}
else{
ps->pbottom=ps->ptop;
ps->ptop->pnext==NULL;
}
}
压栈
void push(pstack ps,int val){
pnode pnew=(pnode)malloc(sizeof(node));
pnew->data=val;
pnew->pnext=ps->ptop;
ps->ptop=pnew;
return;
}
遍历
void traverse(pstack ps){
pnode p=ps->ptop;
while(p!=ps->pbottom){
printf("%d ",p->data);
p=p->pnext;
}
printf("\n");
return;
}
判断是否为空
bool empty(pstack ps){
if(ps->ptop==ps->pbottom){
return true;}
else
return false;
}
出栈
//把ps所指向的栈出栈一次,并把出栈的元素存入pval
bool pop(pstack ps,int*pval){
if(empty(ps))//ps本身存放的就是是的地址
return false;
else{
pnode r=ps->ptop;
*pval=r->data;
ps->ptop=r->pnext;
free(r);
r=NULL;
}
return true;
}
清除
void clear(pstack ps){
if(empty(ps))
return;
else{
pnode p=ps->ptop;
pnode q=NULL;
while(p!=ps->pbottom){
q=p->pnext;
free(p) ;
p=q;
}
ps->ptop=ps->pbottom;
}
return;
}