栈算法【基于顺序表】
(1)代码如下所示:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* 栈的操作实现 */
typedef struct
{
int* data; //堆栈的数据存储区
int top, size; //堆栈的栈顶指针和堆栈的长度
}g_tStack;
//栈的初始化
void StackInit(g_tStack * pstack, int len)
{
if (NULL == pstack) return;
pstack->data = (int*)malloc(sizeof(int) * len);
pstack->size = len;
pstack->top = -1;
return;
}
//判断栈是否为空
bool StackEmpty(g_tStack* pstack)
{ //栈顶指针等于栈元素数量-1的时候,栈满
if ((NULL == pstack)||(-1 >= pstack->top)) return true;
return false;
}
//判断栈是否满
bool StackFull(g_tStack* pstack)
{ //栈顶指针等于-1的时候,栈空
if ((NULL == pstack) || (pstack->top >= pstack->size - 1)) return true;
return false;
}
//向栈中压入数据
bool StackPush(g_tStack* pstack, int data)
{
if ((NULL == pstack) || (StackFull(pstack))) return false;
pstack->top++; //栈顶指针上移
pstack->data[pstack->top] = data; //向栈顶存入数据
return true;
}
//从栈中取出数据
bool StackPop(g_tStack* pstack, int* data)
{
if ((NULL == pstack) || (StackEmpty(pstack))) return false;
*data = pstack->data[pstack->top]; //从栈中取出数据
pstack->top--; //栈顶指针下移
return true;
}
//栈空间的清理
int main()
{
bool ret;
int data;
g_tStack stack; //创建栈对象结构体
StackInit(&stack, 5); //初始化深度为5的栈
for (int i = 0; i < 6; i++) //向栈中压入6个数据,最后一个会报错
{
data = rand() % 100;
ret = StackPush(&stack, data);
if (ret)
printf("push: %d\r\n", data);
else
printf("error\r\n");
}
for (int i = 0; i < 6; i++) //向栈中取出6个数据,最后一个会报错
{
ret = StackPop(&stack, &data);
if (ret)
printf("push: %d\r\n", data);
else
printf("error\r\n");
}
return 0;
}
(2)运行结果如下所示: