严蔚敏版数据结构——顺序栈
其实也是顺序表的一种特殊的操作,实际操作个人觉得要比顺序表还简单。上代码看看:
#include<stdio.h>
#include<malloc.h>
#define OK 1
#define ERROR 0
typedef struct
{
int *base;
int *top;
int stacksize;
}SqStack;
//---------链表的初始化------------
int InitStack(SqStack &S)
{
S.base=(int*) malloc(sizeof(SqStack));
if(S.base==NULL)
return ERROR;
S.top=S.base;
S.stacksize=100;
return OK;
}
//----------入栈---------------------
int Push (SqStack &S,int e)
{
if(S.top-S.base==S.stacksize)
return ERROR;
*S.top=e;//这里要注意先赋值,top再往上移动
S.top++;
return OK;
}
//_-----------打印出来看看-------------
int Print(SqStack S)
{
int i;
int *p;//用来遍历的指针
p=S.base;
for(i=0;i<(S.top-S.base);i++)
{
printf("第%d个数是:%d\n",i+1,*(p+i));
}
return OK;
}
//------------出栈-------------------
int Pop(SqStack &S)
{
int item;
if(S.top==S.base)
{
return ERROR;
}
S.top--; //注意,top是空的,先下移才能得到栈顶元素
item = *S.top;
return item;
}
//----------取栈顶元素---------------
int GetTop(SqStack S)
{
if(S.top!=S.base)
return *(S.top-1); //下移一个才是栈顶
}
int main()
{
int i;
SqStack S;
InitStack(S);
//-----入栈五个数-----
for(i=1;i<=5;i++)
Push(S,i);
Print(S);
//-----出栈-----------
printf("\n出栈元素为:%d",Pop(S));
printf("\n出栈后的栈表如下:\n");
Print(S);
//------打印栈顶元素看看----
printf("\n打印栈顶元素是:%d\n",GetTop(S));
return 0;
}