栈与队列——类
今天考完c++ 前几天复习的时候边缘ob了szk的手写栈和队列 又结合了一下专业的考点补充整合了一下
以下是用模板类(数组)与抽象类(链表)写的queue和stack的push和pop函数以及实例应用
#include <bits/stdc++.h> using namespace std; const int N=1e5+9; template <class T> //队列类模板 class queue { T q[N]; int h,t; public: queue() //初始化 { h=t=-1; } bool empty() { return h==t; } bool full() { return (t+1)%N==h; } void push(T x) //push { if(full()) { puts("full"); } else { q[++t]=x; } } T pop() //pop { if(empty()) { puts("error"); return 0; } h++; return q[h]; } }; template <class T> //栈类模板 class stack { T s[N]; int top; public: stack() //初始化 { top=0; } void push(T x) //push { if(full()) { puts("full"); } s[top++]=x; } T pop() //pop { if(empty()) { puts("error"); return 0; } return s[--top]; } bool empty() { return top==0; } bool full() { return top==N-1; } }; //抽象类------- 链表实现队列和堆栈 class list // 链表 基类 抽象类 { public: list *h; //表头指针 list *t; //表尾指针 list *next; int n; list() { h=t=next=NULL; } virtual void push(int i)=0; //纯虚函数 virtual int pop()=0; }; class que:public list { public: void push(int i) { list *it; it=new que; if(!it) puts("error"); else { it->n=i; if(t) t->next=it; t=it; it->next=NULL; if(!h) h=t; } } int pop() { int i; list *p; if(!h) { puts("empty"); return 0; } else { i=h->n; p=h; h=h->next; return i; } } }; class sta:public list { public: void push(int i) { list *it; it=new sta; if(!it) puts("error"); else { it->n=i; if(h) it->next=h; h=it; it->next=NULL; if(!t) t=h; } } int pop() { int i; list *p; if(!h) { puts("empty"); return 0; } else { i=h->n; p=h; h=h->next; return i; } } }; int main() { queue<int> q; // queue实例化 int num=0,c=0; do { cout<<"Please choose the serve"<<endl; cout<<" 1 要号"<<endl; cout<<" 2 叫号"<<endl; cout<<" 0 退出"<<endl; cin>>c; if(c==1) { q.push(++num); cout<<"您的等待序号为 "<<num<<endl; } else if(c==2) cout<<"请 "<<q.pop()<<" 号客户到柜台办理业务"<<endl; else puts("---quit---"); } while(c); stack<int> st; // stack实例化 int n; cin>>n; while(n) { st.push(n%16); n/=16; } while(!st.empty()) { int a=st.pop(); if(a<9) cout<<a; else cout<<char(a-10+'A'); } cout<<endl; list *p; que Q; p=&Q; p->push(1); cout<<p->pop()<<endl; Q.push(2); cout<<Q.pop()<<endl; return 0; }