#include "stack.h"
#include <iostream>
using namespace std;
int Sta::InitStack( SqStack &S ) //初始化栈
{
// 构造一个空栈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;
}
void Sta::CreateStack( SqStack &S ) //实例栈
{
int num;
InitStack( S );
cout << "请输入" << STACK_INIT_SIZE << "个数" << endl;
for(int i = 0; i < STACK_INIT_SIZE; i++)
{
cin >> num;
Push( S, num );
}
cout << "入栈的数为: " << endl;
Show( S );
}
void Sta::Push( SqStack &S, int e) //入栈
{
if (S.top - S.base >= S.stacksize)
{ //栈满,追加存储空间
S.base = (ElemType *) realloc ( S.base,
(S.stacksize + STACKINCREMENT) *
sizeof (ElemType));
if (!S.base)
exit (OVERFLOW); //存储分配失败
S.top = S.base + S.stacksize;
S.stacksize += STACKINCREMENT; //重新设定存储空间的长度
}
*(S.top++) = e; //入栈
}
int Sta::Pop(SqStack &S, int &e) //出栈,取元素,而不是地址
{
if( S.top == S.base )
{
cout << "栈内的元素已经全部出栈..." << endl
<< "请输入 1 重新建立栈!!!" <<endl;
return ERROR;
}
e = * (--S.top); //出栈
return OK;
}
void Sta::Show( SqStack &S ) //显示栈元素
{
int *L;
L = S.base;
for( ; L < S.top; )
cout << *(L++) << "\t";
cout << endl;
}
void Sta::Trans( SqStack &S ) //数制转换
{
InitStack( S );
int N;
cout << "请输入一个十进制数:" << endl;
cin >> N;
while( N )
{
Push( S, N%2 );
N = N / 2;
}
cout << "对应的二进制数为:" << endl;
int *L;
L = S.top;
for( ; L > S.base; )
cout << *(--L);
cout << endl;
//while ( !StackEmpty(S) )
//{
//int e;
//Pop(S,e);
//cout << e << endl;
//}
}
void Sta::StackEmpty( SqStack &S ) //判断是否为空
{
if( S.base == S.top )
cout << "此时为空栈" << endl;
else
cout << "此时不为空栈" << endl;
}