数据结构和算法——栈的实现

来源:互联网 发布:淘宝破损补寄什么意思 编辑:程序博客网 时间: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