题目
用数组实现栈
解决代码及点评
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <malloc.h>
#include<assert.h>typedef struct Stack
{int nTop;int nLen;int *pnArr;
}Stack, *PStack;//初始化栈 nLen为栈的大小
PStack Create(int nLen)
{if (nLen <= 0){return NULL;}PStack pStack = (PStack)malloc(sizeof(Stack)); pStack->nTop = 0;pStack->nLen = nLen;pStack->pnArr = (int *)malloc(sizeof(int) * nLen);return pStack;
}bool IsEmpty(PStack pStack)
{return pStack->nTop == 0;
}bool IsFull(PStack pStack)
{return pStack->nTop == pStack->nLen;
}void Push(PStack pStack, int nValue)
{if (pStack->nTop == pStack->nLen){printf("栈已满!\n");return;}pStack->pnArr[pStack->nTop] = nValue;pStack->nTop++;
}int Pop(PStack pStack)
{if (pStack->nTop == 0){printf("栈为空!\n");}else{pStack->nTop--;return pStack->pnArr[pStack->nTop];}}void Destroy(PStack pStack)
{free(pStack->pnArr);pStack->pnArr = NULL;free(pStack);pStack = NULL;
}
int main()
{PStack pStack = Create(10);int i;for (i = 0; i < 12; i++){Push(pStack, i);}for (i = 0; i < 10; i++){printf("%d ", Pop(pStack));}Destroy(pStack);system("pause");return 0;
}
代码下载及其运行
代码下载地址:http://download.csdn.net/detail/yincheng01/6858815
解压密码:c.itcast.cn
下载代码并解压后,用VC2013打开interview.sln,并设置对应的启动项目后,点击运行即可,具体步骤如下:
1)设置启动项目:右键点击解决方案,在弹出菜单中选择“设置启动项目”
2)在下拉框中选择相应项目,项目名和博客编号一致
3)点击“本地Windows调试器”运行
程序运行结果