シーヶンススタック
2527 ワード
シーケンススタック(C++)
//
//Description:
//
#include <iostream>
#include <malloc.h>
using namespace std;
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
typedef int Status;
typedef int SElemType;
//
typedef struct
{
SElemType *base;
SElemType *top;
int stacksize;
}SqStack;
//---------------
//
Status InitStack(SqStack &S)
{
S.base = (SElemType *)malloc(STACK_INIT_SIZE*sizeof(SElemType));
if (!S.base)
{
cout << " !" << endl;
return 0;
}
S.top = S.base;
S.stacksize = STACK_INIT_SIZE;
return 1;
}
//
Status Input(SqStack &S, int n)
{
int i;
if (n>0)
{
cout << " " << 1 << " " << endl;
cin >> *S.base;
S.top++;
for (i = 2; i <= n; i++)
{
cout << " " << i << " " << endl;
cin >> *S.top;
S.top++;
}
return 1;
}
else
{
cout << " !" << endl;
return 0;
}
}
//
Status GetTop(SqStack S, SElemType &e)
{
if (S.top == S.base)
{
cout << " , !" << endl;
return 0;
}
e = *(S.top - 1);
cout << " " << e << endl;
return 1;
}
//
Status Push(SqStack &S, SElemType e)
{
if (S.top - S.base >= S.stacksize)
{
S.base = (SElemType *)realloc(S.base, (S.stacksize + STACKINCREMENT)*sizeof(SElemType));
if (!S.base)
{
cout << " !" << endl;
return 0;
}
S.top = S.base + S.stacksize;
S.stacksize += STACKINCREMENT;
}
*S.top++ = e;
return 1;
}
//
Status Pop(SqStack &S, SElemType &e)
{
if (S.top == S.base)
{
cout << " , !" << endl;
return 0;
}
e = *--S.top;
return 1;
}
//--------------
void main()
{
cout << "
-------------------- -----------------" << endl;
SqStack stc;
InitStack(stc);
int num;
cout << " " << endl;
cin >> num;
cout << endl;
Input(stc, num);
SElemType value;
cout << endl;
GetTop(stc, value);
cout << " " << endl;
cin >> value;
cout << endl;
Push(stc, value);
cout << " " << value << endl; GetTop(stc, value);
cout << endl;
Pop(stc, value);
cout << " " << value << endl; GetTop(stc, value);
}