来源:互联网 发布:全球营销网络分布图 编辑:程序博客网 时间:2024/04/30 04:00

数组实现:

#include <iostream>#include <string>using namespace std;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;}}

链表实现:

01list.h

#ifndef LIST_H#define LIST_H 1class List{struct Node{T data;Node* next;Node* prev;Node(const T& d=T()):data(d),next(0){}//零初始化};Node* head;//头指针,用来保存头节点的地址int len;public:List():head(NULL),len(0){ }void push_front(const T& d);//前插List& push_back(const T& d);//尾插int size()const;Node*& getptr(int pos);//找链表中指向指定位置的指针void insert(const T& d, int pos);//在任意位置插入void travel()const;//遍历void clear();//清空这个链表~List();void erase(int pos);//有效位置为0~size()-1void remove(const T& d);int find(const T& d)const;void set(int pos, const T& d);bool empty()const{return head==NULL;}const T& front()const{if(empty())throw "空";return head->data;}const T& back()const;};#endif


#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;}}


0 0
原创粉丝点击