基于顺序栈的基本操作的实现
来源:互联网 发布:freebsd 在线安装软件 编辑:程序博客网 时间:2024/06/05 23:56
顺序栈简介:栈(限定在表尾进行插入和删除操作的线性表)的顺序储存结构称为顺序栈。顺序栈本质是顺序表的简化,唯一需要确定的就是用数组的哪一端表示栈低。
文章内容:初始化栈、入栈、出栈、取栈顶、判断栈是否为空等操作的代码以及实现结果截图
顺序栈类的定义:
#include<iostream>#include<iomanip> //使用了setw()using namespace std;const int StackSize=100;template<class T>class SeqStack{public:SeqStack(){top=-1;} /*初始化一个空栈*/~SeqStack(){};void Push(T x); /*将x入栈*/T Getpop(){if(top!=-1) return data[top];}; /*弹出栈顶元素*/T Pop(); /*出栈*/int Empty(){ /*判断栈是否为空*/if(top==-1) { return 1;}else{return 0;} }private:T data[StackSize]; /*存放栈元素的数组*/int top;};
成员函数的定义:
template<class T>void SeqStack<T>::Push(T x){if(top==StackSize) throw "上溢";else{ data[++top]=x;}} template<class T>T SeqStack<T>::Pop(){ if(top==-1) throw"下溢"; else{T x; x=data[top--];return x; } }
主函数:
int main(){ int w; cout<<'\n'<<"请选择您要输入的数据类型:"<<endl; cout<<"1.int类型"<<'\t'<<"2.char类型"<<'\n'<<endl; cin>>w; switch(w) { case 1: { int i; SeqStack<int>one; one.Push(100); one.Push(200); one.Push(300); cout<<'\n'<<"请输入入栈元素"<<endl; cin>>i; one.Push(i); if(one.Empty()) { cout<<"您的栈为空!"; } else { cout<<"您的栈有元素!"; cout<<'\n'<<endl;; cout<<"栈顶元素为:"; cout<<one.Getpop(); cout<<'\n'<<"弹出栈顶元素:"; cout<<one.Pop(); cout<<'\n'<<"此时栈顶元素为:"; cout<<one.Getpop(); } } break; case 2: { char i; SeqStack<char>one; one.Push('k'); one.Push('j'); one.Push('i'); cout<<'\n'<<"请输入入栈元素"<<endl; cin>>i; one.Push(i); if(one.Empty()) { cout<<"您的栈为空!"; } else { cout<<"您的栈有元素!"; cout<<'\n'<<endl;; cout<<"栈顶元素为:"; cout<<one.Getpop(); cout<<'\n'<<"弹出栈顶元素:"; cout<<one.Pop(); cout<<'\n'<<"此时栈顶元素为:"; cout<<one.Getpop(); } } break; } cout<<'\n'<<endl; return 0;}
运行结果:
心得:
1. 通过自己亲自执行代码明白了为什么实现顺序栈的时间复杂度均为O(1)。
2. 编写代码的过程体会到顺序栈的结构简单的优点,相比较顺序栈更加简化。
3. 编写代码后体会到用顺序存储结构表示的栈并不存在插入和删除数据元素需要移动元素的问题;同时也明白了顺序栈容量也是难以扩充的。
阅读全文
0 0
- 基于顺序栈的基本操作的实现
- 实现基于静态数组的顺序表的基本操作
- 顺序栈的基本操作实现
- 顺序栈的基本操作实现
- 顺序栈的基本操作实现
- 1044 顺序栈基本操作的实现
- 顺序栈的基本操作实现c++
- php实现顺序栈的基本操作
- 顺序表实现栈的基本操作
- 顺序栈的基本操作
- 顺序栈的基本操作....
- 顺序栈的基本操作
- 顺序栈的基本操作
- 顺序栈的基本操作
- 顺序栈的基本操作
- 顺序栈的基本操作
- 顺序栈的基本操作
- 顺序栈的基本操作
- 2. Add Two Numbers
- POJ3294-Life Forms
- CS231n学习笔记--12.Visualizing and Understanding
- Android进阶四:Databinding的使用(基础篇)
- 【安全牛学习笔记】Syn-Flood、IP地址欺骗
- 基于顺序栈的基本操作的实现
- 总结(2017年上)
- css动画
- Ubuntu 下安装配置 Jenkins
- 合作协同进化算法概述(Cooperative Coevolution)
- 南阳理工oj 746 整数划分(四) 区间dp
- 微信测试号首次开发总结
- python 列表推导式
- Codeforces-242C:King's Path(BFS+map)