#include<stdio.h>
#include<malloc.h>
#include<iostream>
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
using namespace std;
typedef int ElemType;
typedef int Status;
typedef struct
{
ElemType *base;
ElemType *top;
int stacksize;
} SqStack;
Status InitStack(SqStack &S)
{
S.base = (ElemType*)malloc(STACK_INIT_SIZE*sizeof(ElemType));
if (!S.base)
exit(OVERFLOW);
S.top = S.base;
S.stacksize = STACK_INIT_SIZE;
return OK;
}
Status DestroyStack(SqStack &S)
{
S.top = NULL;
S.stacksize = 0;
free(S.base);
return OK;
}
Status ClearStack(SqStack &S)
{
S.top = S.base;
return OK;
}
Status StackEmpty(SqStack S)
{
if (S.top == S.base)
return ERROR;
else
return TRUE;
}
Status StackLength(SqStack S)
{
if (S.top == S.base)
return FALSE;
else
return (S.top - S.base);
}
Status GetTop(SqStack S, ElemType &e)
{
if (S.top == S.base)
return FALSE;
else
e = *(S.top - 1);
return e;
}
Status Push(SqStack &S, ElemType &e)
{
if (S.top - S.base >= STACK_INIT_SIZE)
{
S.base = (ElemType *)realloc(S.base, (S.stacksize + STACKINCREMENT) * sizeof(ElemType));
if (!S.base)
{
return false;
}
S.top = S.base + STACK_INIT_SIZE;
S.stacksize = S.stacksize + STACKINCREMENT;
}
*S.top++= e;
return OK;
}
Status Pop(SqStack &S, ElemType &e)
{
if (S.top == S.base)
return ERROR;
else
{
e = *--S.top;
return e;
}
}
Status StackTraverse(SqStack S)
{
if (S.base == NULL)
return ERROR;
if (S.top == S.base)
printf("栈中没有元素\n");
ElemType *p;
p = S.top;
while (p > S.base)
{
p--;
printf("%d ",*p);
}
printf("\n\n");
return OK;
}
int main()
{
SqStack S;
InitStack(S);
int i,n,e ;
printf("输入栈的长度:\n");
scanf("%d",&n);
printf("输入栈的元素\n");
for (i = 1; i <= n; i++)
{
++S.top;
scanf("%d",S.top-1);
}
if (StackEmpty(S) == 1)
printf("栈非空\n\n");
else
printf("栈为空\n\n");
printf("栈的长度是:%d\n\n",StackLength(S));
printf("遍历输出栈中的所有元素:\n");
StackTraverse(S);
cout<<"栈顶元素是:"<<GetTop(S,e)<<endl;
printf("请输入要插入的元素的数值:\n");
cin>>e;
Push(S,e);
printf("现在栈中的元素是:\n");
StackTraverse(S);
printf("删除栈顶元素:\n");
cout<<"被删元素是:"<<Pop(S,e)<<endl<<endl;
printf("现在栈中的元素是:\n");
StackTraverse(S);
return 0;
}