/*
顺序栈的实现:
初始化
入栈
出栈
计算栈的有效数据长度
获取栈顶数据
清空栈
销毁栈
*/
#include <stdio.h>
#include <stdlib.h>
#define ElemType int
typedef struct __stackInfo
{
ElemType *data;
unsigned int top;
unsigned int capacity;
} stackInfo;
/* 初始化 */
int initStack(stackInfo **ppS, unsigned int size)
{
if (NULL == ppS)
{
printf("ppNewStack point address is not exist\n");
return -1;
}
stackInfo *pNewStack = (stackInfo *)malloc(sizeof(stackInfo));
if (NULL == pNewStack)
{
printf("ppNewStack malloc fail\n");
return -1;
}
pNewStack->data = (ElemType *)malloc(sizeof(ElemType)*size);
if (NULL == pNewStack->data)
{
printf("ppNewStack databuf malloc fail\n");
/* 前面几篇代码就少了这里,务必要小心,记个坑: 一旦直接推出,则泄漏内存pNewStack */
free(pNewStack);
return -1;
}
pNewStack->capacity = size;
pNewStack->top = 0;
*ppS = pNewStack;
return 0;
}
/* 入栈 */
int pushStack(stackInfo *pS, int val)
{
if (NULL == pS)
{
printf("pStack point NULL\n");
return -1;
}
if (pS->capacity == pS->top)
{
printf("pStack full\n");
return -1;
}
pS->data[pS->top] = val;
pS->top++;
return 0;
}
/* 出栈 */
int popStack(stackInfo *pS, int *val)
{
if ((NULL == pS) || (NULL == val))
{
printf("pStack point NULL or val point NULL\n");
return -1;
}
if (pS->top <= 0)
{
printf("pStack empty\n");
return -1;
}
pS->top--;
*val = pS->data[pS->top];
return 0;
}
/* 获取栈顶数据 */
int topStack(stackInfo *pS, int *val)
{
if ((NULL == pS) || (NULL == val))
{
printf("pStack point NULL or val point NULL\n");
return -1;
}
if (0 >= pS->top)
{
printf("pStack empty\n");
return -1;
}
*val = pS->data[pS->top - 1];
return 0;
}
/* 计算栈中有效数据长度 */
int lengthOfStack(stackInfo *pS, unsigned int *val)
{
if ((NULL == pS) || (NULL == val))
{
printf("pStack point NULL or val point NULL\n");
return -1;
}
*val = pS->top;
return 0;
}
/* 清空栈 */
int emptyStack(stackInfo *pS)
{
if (NULL == pS)
{
printf("pStack point NULL\n");
return -1;
}
while(pS->top)
{
/* 小技巧:如果赋值为0即0,如果赋值为FF,因16、32位平台的区别,鉴于可移植性考虑,赋值为0按位取反 */
pS->data[pS->top--] = ~0;
}
return 0;
}
/* 销毁栈 */
int destoryStack(stackInfo **ppS)
{
if (NULL == ppS)
{
printf("pStack point address is not exist\n");
return -1;
}
if (NULL == *ppS)
{
printf("pStack point NULL\n");
return -1;
}
emptyStack(*ppS);
/* 关注点:1、两块动态内存需释放 2、注意释放的先后顺序 */
free((*ppS)->data);
free(*ppS);
return 0;
}
/* 测试入口 */
int main(void)
{
stackInfo *pNewStack = NULL;
unsigned int length = 0;
int val = 0;
initStack(&pNewStack, 10);
lengthOfStack(pNewStack, &length);
printf("pNewStack valid length: %d\n", length);
/* 创建10个元素的栈,入栈11次,检查软件的容错机制 */
for (int i=0; i<11; i++)
{
pushStack(pNewStack, i);
lengthOfStack(pNewStack, &length);
printf("pNewStack valid length: %d\n", length);
}
/* 入栈10个数据,出栈11次,检查软件的容错机制 */
for (int i=0; i<11; i++)
{
topStack(pNewStack, &val);
printf("pNewStack top data: %d\n", val);
popStack(pNewStack, &val);
printf("popStack data: %d\n", val);
}
emptyStack(pNewStack);
lengthOfStack(pNewStack, &length);
printf("pNewStack valid length: %d\n", length);
destoryStack(&pNewStack);
return 0;
}
原文地址:https://www.cnblogs.com/tedani/p/9990684.html