栈的基本操作
来源:互联网 发布:域名和商标的区别 编辑:程序博客网 时间:2024/05/21 10:29
/*程序的版权和版本声明部分:*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);//取栈顶元素给ebool 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;}
运行结果:
0 0
- 栈的基本操作
- 栈的基本操作
- 栈 的基本操作。
- 栈的基本操作
- 栈的基本操作
- 栈的基本操作
- 栈的基本操作
- 栈的基本操作
- 栈的基本操作
- 栈的基本操作
- 栈的基本操作
- 栈的基本操作
- 栈的基本操作
- 栈的基本操作
- 栈的基本操作
- 栈的基本操作
- 栈的基本操作
- 栈的基本操作
- TestThinking
- zoj 1629 - Counting Triangles
- 示波器探头基础入门指南(上)
- 【Linux】Linux是怎么启动的
- Linux常用命令总结(二)--系统命令
- 栈的基本操作
- Oracle锁表与解锁
- Codeforces Round #265 (Div. 2)
- svn文件冲突,树冲突详解
- OC 继承
- 快播5.0永不升级版 孤雨定制骨头版
- 通过Web远程浏览并控制6410上的摄像头
- junit4测试
- 调整linux系统时间和时区与Internet时间同步