#include "stdafx.h"
#include<iostream>
using namespace std;
#include<malloc.h>
typedef int ElemType;
#define OK 1 //正确
#define ERROR 0 //失败
#define STACK_INIT_SIZE 5 //栈的初始化容量
#define STACK_INCREAMENT 2 //栈满之后,增加的容量
typedef struct Stack
{
ElemType *base; //栈低指针
ElemType *top; //栈顶指针
int stacksize; //栈的最大容量
}SqStack;
//初始化
void InitStack(SqStack &S)
{
S.base=(ElemType *)malloc(STACK_INIT_SIZE * sizeof(ElemType));
if(!S.base) return;
S.top=S.base;
S.stacksize = STACK_INIT_SIZE;
}
//获取栈顶元素
void GetTop(SqStack &S)
{
if(S.top==S.base)
{
cout<<"栈内没有元素"<<endl;
return;
}
cout<<"栈顶元素是:"<<*(S.top-1)<<endl;
}
//进栈
void Push(SqStack &S,ElemType e)
{
if(S.top-S.base>=S.stacksize)
{
cout<<"栈满了,继续为其分配空间 ... "<<endl;
//realloc 函数
S.base=(ElemType *)realloc(S.base,(S.stacksize+STACK_INCREAMENT) * sizeof(ElemType));
if(!S.base) return;
S.top=S.base+S.stacksize;
S.stacksize += STACK_INCREAMENT;
}
*S.top++=e;
//S.top++;
}
//出栈
void Pop(SqStack &S)
{
if(S.top==S.base)
{
cout<<"栈内没有元素"<<endl;
return;
}
cout<<"出栈的元素是:"<<*--S.top<<endl; //先使指针减1,然后取值,相当于*(S.top-1);S.top--;
}
int main(int argc,char* argv[])
{
SqStack s;
int e;
InitStack(s);
Push(s,1);
Push(s,2);
Push(s,3);
Pop(s);
Pop(s);
Pop(s);
GetTop(s);
Push(s,4);
Push(s,5);
Pop(s);
Push(s,6);
Push(s,7);
GetTop(s);
Push(s,8);
Push(s,9);
Push(s,10);
Pop(s);
Pop(s);
Pop(s);
Pop(s);
Pop(s);
Pop(s);
Pop(s);
Pop(s);
cin>>e;
return 0;
}