栈
定义
- 一种可以实现“先进后出”的存储结构,栈类似箱子
分类
- 静态栈
- 动态栈
算法
- 出栈
- 压栈
应用
- 函数调用
- 中断
- 表达式求值
- 内存分配
- 缓冲处理
- 迷宫
代码
//stack.cpp
#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);
void push(PSTACK, int);
void traverse(PSTACK);
bool pop(PSTACK, int *);
void clear(PSTACK);
int main(void)
{
STACK S; //STACK等价于struct Stack
int val;
init(&S); //目的是造出一个空栈
push(&S,1);
push(&S,2);
clear(&S);
if( pop(&S, &val) )
{
printf("%d \n", val);
}
else
{
printf("shibia");
}
traverse(&S);
clear(&S);
traverse(&S);
system("PAUSE");
return 0;
}
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; //等价于 pS->pBottom->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;
}
}
bool pop(PSTACK pS, int * pVal)
{
if( empty(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;
}
}
本文来自博客园,作者:小恒2020,转载请注明原文链接:https://www.cnblogs.com/xiaoheng2020/p/12668487.html