参考 http://blog.youkuaiyun.com/liujiuxiaoshitou/article/details/53394888
#include<iostream>
#include<stdlib.h>
#include<stdio.h>
#include<math.h>
#define ERROR 0
#define OK 1
#define STACK_INIT_SIZE 2
#define STACKINCREMENT 1
#define OVERFLOW -2
typedef int Status;
typedef int SElemType;
using namespace std;
typedef struct
{
SElemType *top; //栈顶指针
SElemType *base; // 栈底指针
int stacksize; //栈大小
} SqStack;
//构造栈
Status initStack(SqStack &S)
{
S.base=(SElemType * )malloc
(STACK_INIT_SIZE*sizeof(SElemType)); //分配STACK_INIT_SIZE*SElemType大小空间
//并且把首地址返回给S.base
if(!S.base) // x=0 !x=1
exit(OVERFLOW);
S.top=S.base;
S.stacksize=STACK_INIT_SIZE;
return OK;
}
//销毁栈
Status DestoryStack(SqStack &S)
{
S.top=NULL;
S.stacksize=0;
free(S.base); //释放空间
S.base=NULL; //将base=NULL防止出现野指针
return OK;
}
//栈顶插入
void Push(SqStack &S)
{ int e;
int q=STACK_INIT_SIZE;
int p=STACKINCREMENT;
while(cin>>e)
{
if(S.top-S.base>= q)
{
S.base=(SElemType *)realloc(S.base,(S.stacksize+p)*sizeof(SElemType));
S.top=S.base+q;
S.stacksize=S.stacksize+q;
q=q+p;
}
S.top++;
*(S.top-1)=e;
}cin>>e;
}
//遍历栈
Status StackTraverse(SqStack S)
{
if(S.base ==NULL)
return ERROR;
if(S.top==S.base)
cout<<"栈中无元素"<<endl;
SElemType *p;
p=S.top;
while(p>S.base)
{
p--;
cout<<*p;
}
return OK;
}
Status StackOutput(SqStack S)
{
SElemType *head;
head=S.base;
while(S.base!=S.top)
{
cout<<*(S.base);
S.base++;
}S.base=head;
}
int main()
{
SqStack S;
initStack(S);
Push(S); StackOutput(S);
//StackTraverse(S);
}