数据结构和算法——栈的实现
来源:互联网 发布:淘宝破损补寄什么意思 编辑:程序博客网 时间:2024/06/11 19:22
一 用数组实现
02stack.cpp
<span style="font-size:18px;">#include <iostream>using namespace std;#include <string>typedef string T;class Stack{T a[5];int cur;public:Stack():cur(0){}void push(const T& d)throw(const char*);//数据入栈成为栈顶T pop()throw(const char*);//栈顶数据出栈,下一个数据成为栈顶const T& top()const throw(const char*);//取得栈顶数据bool empty()const{return cur==0;}//是否空栈bool full()const{return cur==5;}//是否已满void clear(){cur=0;}//栈清空(复位)int size()const{return cur;}//栈中数据个数};void Stack::push(const T& d)throw(const char*){if(full()) throw "满";a[cur++] = d;}T Stack::pop()throw(const char*){if(empty()) throw "空";return a[--cur];}const T& Stack::top()const throw(const char*){if(empty()) throw "空";return a[cur-1];}int main(){Stack s;try{s.push("芙蓉");s.push("凤姐");s.push("春哥");s.push("曾哥");s.push("权哥");s.push("犀利");}catch(const char* e){cout << "异常:" << e << endl;}while(!s.empty()){cout << s.pop() << endl;}}</span>
二 用链表实现
03stack.cpp
<span style="font-size:18px;">#include <iostream>using namespace std;typedef int T;#include "01list.h"//见上节博文class Stack{List l;public:void push(const T& d);//数据入栈成为栈顶T pop();//栈顶数据出栈,下一个数据成为栈顶const T& top()const;//取得栈顶数据bool empty()const{return l.empty();}//是否空栈bool full()const{return false;}//是否已满void clear(){l.clear();}//栈清空(复位)int size()const{return l.size();}//栈中数据个数};void Stack::push(const T& d){l.push_front(d);}T Stack::pop(){T t = l.front();l.erase(0);return t;}const T& Stack::top()const {return l.front();}int main(){Stack s;try{s.push(1);s.push(2);s.push(3);s.push(4);s.push(5);s.push(6);}catch(const char* e){cout << "异常:" << e << endl;}while(!s.empty()){cout << s.pop() << endl;}}</span>
0 0
- 数据结构和算法——栈的实现
- 数据结构和算法--栈的数组实现
- 数据结构和算法--栈的链式实现
- 数据结构和算法——队列的实现
- 数据结构算法代码实现——栈和队列(一)
- 数据结构算法代码实现——栈和队列(二)
- 《数据结构与算法分析》—栈的链表和数组实现(C语言)
- 数据结构——KMP算法的实现
- 【数据结构和算法】【栈】顺序栈的代码实现
- 数据结构和算法--队列的数组实现
- 数据结构和算法--队列的链式实现
- 数据结构和算法------ArrayList的实现
- 数据结构和算法------LinkedList的实现
- 数据结构和算法------AVLTree的实现
- 基本数据结构和算法的前端实现
- 数据结构和算法--二叉树的实现
- 大话数据结构—数据结构和算法的关系
- 【数据结构和算法】java实现栈结构
- __FILE__,__LINE__,__DATE__,__TIME__,__STDC__ 宏定义
- WebViewClient与WebChromeClient 区别
- It's the Star or Over?
- 多重继承和虚继承的内存布局
- android中layout的背景
- 数据结构和算法——栈的实现
- AC自动机+记忆化搜索uva1399Puzzle
- DPDK helloworld
- 渲染流程
- CentOS6.4 配置LVS(DR模式)
- Ngnix服务器下面的强身份认证登陆的实现
- java—基础知识总结
- 按返回键时不销毁当前activity
- Linux软件开发工程师