例:从键盘上输入一批整数,然后按照相反的次序打印出来。
.h文件:
/* 栈的顺序存储 */
//初始化
void InitStack(Stack &S)
{
S.top = -1;
}
//清空栈
void ClearStack(Stack &S)
{
S.top = -1;
}
//检查一个栈是否为空
int StackEmpty(Stack &S)
{
return (S.top == -1);
}
//获取栈顶元素
ElemType Peek(Stack &S)
{
if(S.top == -1)
{
cerr<<"Stack is empty!"<<endl;
exit(1);
}
return S.stack[S.top];
}
//入栈操作
void Push(Stack &S,const ElemType &item)
{
if(S.top == StackMaxSize - 1)
{
cerr<<"Stack overflow!"<<endl;
exit(1);
}
S.top++;
S.stack[S.top] = item;
}
//出栈操作
ElemType Pop(Stack &S)
{
if(S.top == -1)
{
cerr<<"Stack is empty!"<<endl;
exit(1);
}
ElemType temp = S.stack[S.top];
S.top--;
return temp;
}
//检查栈是否已满
int StackFull(Stack &S)
{
return (S.top == StackMaxSize - 1);
}
.cpp文件
#include <iostream>
using namespace std;
typedef int ElemType;
const int StackMaxSize = 50;
struct Stack
{
ElemType stack[StackMaxSize];
int top;
};
#include "stack.h"
int main()
{
Stack S;
InitStack(S);
ElemType x;
while(cin>>x && x != -1)
{
Push(S,x);
}
while(!StackEmpty(S))
{
cout<<Pop(S)<<" ";
}
cout<<endl;
return 0;
}