***栈:***由一个固定大小的数组和一个栈顶top组成(操作类似于线性表)
#include <iostream>
#include <memory.h>
#include <queue>
#include <list>
#define MaxSize 100
typedef char ElemType;
using namespace std;
struct SqStack
{
ElemType data[MaxSize];
int top; //栈指针
};
void InitStack(SqStack * &s);//初始化栈
void ClearStack(SqStack *&s);//释放栈
int StackLenth(SqStack * s);//求栈s的长度
int StackEmpty(SqStack * s);//判断栈s是否为空栈
int Push(SqStack * &s, ElemType e);//进栈元素e
int Pop(SqStack * &s, ElemType &e);//出栈一个元素
int GetTop(SqStack * s, ElemType &e);//取出栈顶元素
void DispStack(SqStack * s);//从栈顶到栈底输出元素
int main()
{
ElemType e;
SqStack *s;
cout << "(1)初始化栈s\n";
InitStack(s);
cout << "(2)栈为";
cout << (StackEmpty(s) ? "空" : "非空") << "\n";
cout << "(3)依次进栈元素a,b,c,d,e\n";
Push(s, 'a');
Push(s, 'b');
Push(s, 'c');
Push(s, 'd');
Push(s, 'e');
cout << "(4)栈为";
cout << (StackEmpty(s) ? "空" : "非空") << "\n";
cout << "(5)栈长度:" << StackLenth(s) << "\n";
cout << "(6)从栈顶到栈底元素:";
DispStack(s);
cout << "(7)出栈序列:";
while (!StackEmpty(s))
{
Pop(s, e);
cout << e;
}
cout << endl;
cout << "(8)栈为";
cout << (StackEmpty(s) ? "空" : "非空") << "\n";
cout << "(9)释放栈\n";
ClearStack(s);
return 0;
}
void InitStack(SqStack *& s)
{
s = new SqStack[sizeof(SqStack)];
s->top = -1;
}
void ClearStack(SqStack *& s)
{
delete[]s;
}
int StackLenth(SqStack * s)
{
return(s->top + 1);
}
int StackEmpty(SqStack * s)
{
return (s->top == -1);
}
int Push(SqStack *& s, ElemType e)
{
if (s->top == MaxSize - 1)
return 0;
s->top++;//栈顶加1
s->data[s->top] = e;//栈顶当前位置存入数据
return 1;
}
int Pop(SqStack *& s, ElemType & e)
{
if (s->top == -1)
return 0;
e = s->data[s->top];
s->top--;
return 1;
}
int GetTop(SqStack * s, ElemType & e)
{
if (s->top == -1)
return 0;
e = s->data[s->top];
return 1;
}
void DispStack(SqStack * s)
{
int i;
for (i = s->top; i >= 0; i--)
{
cout << s->data[i] << " ";
}
cout << endl;
}