///ADTstack///
// data 相邻元素具有前驱和后继关系
// operation
// InitStack(*S) 初始化操作,建立一个空栈
// DestroyStack(*S)若栈存在,则销毁它
// ClearStack(*S) 将栈清空
// StackEmpty(*S) 若栈为空 返回true 否则返回false
// GetTop(S, *e) 若为非空则返回栈顶元素e
// Push(*S, e) 将元素e压入栈中
// Pop(*S, e)将元素出栈 并返回其值
// StackLength(S) 返回栈S元素个数
//
///endADT/
// data 2012 12 20 by oujiayao
//
# include <iostream>
# define MAXSIZE 20
using namespace std;
typedef struct
{
int data[MAXSIZE];
int top; //栈顶指针
}SqStack;
void InitStack(SqStack *S)
{
S->top = -1;
}
bool StackEmpty(SqStack *S)
{
if(S->top == -1)
return true;
else
return false;
}
void Push(SqStack *S, int a, int b, int c, int d, int e)
{
if(S->top == MAXSIZE-1) //栈满不能入栈
{
exit(0);
}
else
{
S->top++; //这样栈指针才能指向0
S->data[S->top] = a;
S->top++;
S->data[S->top] = b;
S->top++;
S->data[S->top] = c;
S->top++;
S->data[S->top] = d;
S->top++;
S->data[S->top] = e;
}
}
void Pop(SqStack *S)
{
int elem;
if(S->top == -1)
{
exit(0);
}
else
{
elem = S->data[S->top];
S->top--;
}
}
void printStack(SqStack *S)
{
int i;
cout << "\n\n栈表的输出:" << endl;
for(i=S->top; i>=0; i--)
cout << S->data[i] << endl;
}
int GetTop(SqStack S)
{
return S.data[S.top];
}
int StackLength(SqStack S)
{
int count=0, j;
for(j=S.top; j>=0; j--)
count++;
return count;
}
int main(void)
{
SqStack S;
cout << "初始化一个空栈:" << endl;
InitStack(&S);
if(!StackEmpty(&S))
{
cout << "栈是空的!" << endl;
}
else
{
cout << "压入5个数据:";
Push(&S, 1, 2, 3, 4, 5);
printStack(&S);
cout<< "\n\n栈顶元素是:" << GetTop(S);
cout<< "\n\n栈的长度是:" << StackLength(S) << endl;
}
cout << "\n\n出栈的第一个元素并显示:";
Pop(&S);
printStack(&S);
return 0;
}