/*程序的版权和版本声明部分:
*Copyright(c)2014,烟台大学计算机学院学生
*All rights reserved.
*文件名称:
*作者:田成琳
*完成日期:2014 年 9 月 16 日
*版本号:v1.0
*对任务及求解方法的描述部分:
*问题描述:栈的基本操作
*程序输入:栈元素
*程序输出:
*问题分析:
*算法设计:
*/
#include <iostream>
#include <cstdlib>
using namespace std;
const int MaxSize = 50;
struct SqStack
{
int data[MaxSize];
int top; //栈顶指针
};
void InitStack(SqStack *&s);//初始化栈
void DestoryStack(SqStack *&s);//销毁栈
bool StackEmpty(SqStack *s);//判断栈是否为空
bool Push(SqStack *s,int &e);//进栈
bool Pop(SqStack *s);//出栈
bool GetTop(SqStack *s,int &e);//取栈顶元素给e
bool StackDisplay(SqStack *s);//输出栈内所有元素
void InitStack(SqStack *&s)//初始化栈
{
s=(SqStack *)malloc(sizeof(SqStack));
s->top=-1;
}
void DestoryStack(SqStack *&s)//销毁栈
{
free(s);
}
bool StackEmpty(SqStack *s)//判断栈是否为空
{
return (s->top==-1);
}
bool Push(SqStack *s,int &e)//进栈
{
if(s->top==MaxSize-1)
return false;
else
{
s->top++;
s->data[s->top]=e;
}
return true;
}
bool Pop(SqStack *s)//出栈
{
if(s->top==-1)
return false;
else
s->top--;
return true;
}
bool GetTop(SqStack *s,int &e)//取栈顶元素给e
{
if(s->top==-1)
return false;
else
e=s->data[s->top];
return true;
}
bool StackDisplay(SqStack *s)//输出栈内所有元素
{
if(s->top==-1)
return false;
else
{
for(int i=s->top; i>=0; i--)
cout<<s->data[i]<<" ";
cout<<endl;
}
return true;
}
int main()
{
SqStack *s;
int n,number;
cout<<"现在要初始化栈..."<<endl;
InitStack(s);
cout<<"初始化成功,现在将要添加元素。请输入添加元素的个数:"<<endl;
cin>>n;
cout<<"请输入要添加的"<<n<<"个元素:"<<endl;
for(int i=0; i<n; i++)
{
cin>>number;
Push(s,number);
}
cout<<"栈现在不为空,栈顶元素是:"<<endl;
GetTop(s,number);
cout<<number<<endl;
cout<<"栈内元素为:"<<endl;
StackDisplay(s);
cout<<"现在将把栈顶元素弹出栈..."<<endl;
Pop(s);
cout<<"栈顶元素出栈后";
if(StackEmpty(s))
cout<<"栈为空。"<<endl;
else
{
cout<<"栈内元素为:"<<endl;
StackDisplay(s);
}
return 0;
}
运行结果: