顺序栈的操作
来源:互联网 发布:反电信网络诈骗 编辑:程序博客网 时间:2024/06/11 18:58
#include <iostream>#include <stdlib.h>#define STACK_INIT_SIZE 100#define STACKINCREMENT 10#define ERROR -1#define OK 1#define OVERFLOW -1using namespace std;typedef struct{ int *base; int *top; int stacksize;} SqStack;int InitStack(SqStack &S){ S.base=(int*)malloc(STACK_INIT_SIZE*(sizeof(int))); if(!S.base) exit(OVERFLOW); S.top=S.base; S.stacksize=STACK_INIT_SIZE; return OK;}int GetTop(SqStack S,int &e){ if(S.top==S.base) return ERROR; e=*(S.top-1); return OK;}int Push(SqStack &S,int e){ if(S.top-S.base>=S.stacksize) { S.base=(int*)realloc(S.base,(S.stacksize+STACK_INIT_SIZE)*sizeof(int)); if(!S.base) exit(OVERFLOW); S.top=S.base+S.stacksize; S.stacksize+=STACK_INIT_SIZE; } *S.top++=e; return OK;}int Pop(SqStack &S, int &e){ if(S.top==S.base) return ERROR; e=*(--S.top); return OK;}void ElemSqstack(SqStack S){ if(S.top==S.base) { cout<<"栈内没有元素!"<<endl; return; } cout<<"栈内元素为:"; while(S.top!=S.base) { cout<<*(--S.top)<<" "; } cout<<endl;}int main(){ SqStack S; InitStack(S); cout<<"请输入压入元素个数:"<<endl; int n; cin>>n; int a; cout<<"请依次输入入栈元素:"<<endl; for(int i=0; i<n; i++) { cin>>a; Push(S,a); } ElemSqstack(S); int chose; cout<<"1. 入栈 2.出栈 3.取栈顶元素 4.退出"<<endl; cin>>chose; while(chose!=4) { if(chose==1) { //cout<<"入栈"<<endl; int q; cout<<"想要入栈的元素为:"; cin>>q; Push(S,q); ElemSqstack(S); } else if(chose==2) { int e; //cout<<"pop()"<<Pop(S, e)<<endl; //cout<<"出栈"<<endl; if(S.top==S.base) { cout<<"栈已经为空,不能出栈!"<<endl; cout<<endl; } else { Pop(S, e); cout<<"出栈的元素为:"<<e<<endl; ElemSqstack(S); cout<<endl; } } else if(chose==3) { int m; if(GetTop(S,m)==-1) { cout<<"栈为空!"<<endl; cout<<endl; } else { cout<<"栈顶元素:"<<m<<endl; ElemSqstack(S); } } else if(chose==4) break; else { cout<<"请重新选择!"<<endl; // cout<<"1. 入栈 2.出栈 3.退出"<<endl; } cout<<"1. 入栈 2.出栈 3.取栈顶元素 4.退出"<<endl; cin>>chose; } cout<<"结束"<<endl; return 0;}
0 0
- 顺序栈的操作
- 顺序栈的操作
- 顺序栈的操作
- 顺序栈的操作
- 顺序栈的操作
- 顺序栈的操作
- 顺序栈的基本操作
- 顺序栈的一些操作
- 顺序栈的基本操作....
- 顺序栈的基本操作
- 顺序栈的相关操作
- 顺序栈的相关操作
- 顺序栈的各种操作.
- 顺序栈的一般操作
- 顺序栈的基本操作
- 顺序栈的常用操作
- 顺序栈的基本操作
- 顺序栈的一些操作
- Shell脚本输出斐波拉契数列前十项,每行显示两个数
- [学习笔记]学习主题模型(Topic Model)和PLSA( probabilistic latent semantic analysis)
- 顺序栈实现括号匹配
- Android如何解决异常问题
- 深入理解JVM03--理解GC日志
- 顺序栈的操作
- Spring JMS---三种消息监听器
- 浮点数的原罪
- 类的成员变量,对象,静态变量
- Hive 远程模式安装
- 每日一题之动归-换钱的最少次数(二)
- Git Stash用法
- 树的遍历
- 【Leetcode】Customers Who Never Order