c++利用循环数组建立FIFO模板队列

可直接编译运行,其中status()方法效果如图:

c++利用循环数组建立FIFO模板队列

1 #include <iostream>
 2 using std::cout;
 3 
 4 template<typename T>
 5 class Queue
 6 {
 7     public:
 8         Queue(int maxn=1000):m_size(0),MAXN(maxn),m_front(0),m_rear(0){head=new T[maxn];}
 9         int size()const{return m_size;}
10         bool empty()const{return m_size==0?false:true;}
11         T front()const{return m_size?head[m_front]:T();}
12         T back()const{return m_size?head[m_rear]:T();}
13         bool clear(){m_size=m_front=m_rear=0;delete []head;}
14         bool push(const T&);
15         T pop();
16         void status();
17     private:
18         int MAXN;
19         int m_front,m_rear;
20         T *head;
21         int m_size;
22 };
23 
24 
25 int main()
26 {
27     Queue<char> q;
28     for(int i=0;i<10;i++)
29         q.push('a'+i);
30     q.status();
31     cout<<"nq.pop()="<<q.pop()<<"n";
32 
33 
34     return 0;
35 }
36 
37 
38 template<typename T>
39 bool Queue<T>::push(const T& t)
40 {
41     if( 0==m_size && NULL == head )
42     {head=new T[MAXN];m_rear=m_front=0;}
43     if(m_size>=MAXN)return false;
44     else
45     {
46         head[m_rear]=t;
47         m_rear=(m_rear+1)%MAXN;
48         m_size++;
49         return true;
50     }
51 }
52 
53 template<typename T>
54 T Queue<T>::pop()
55 {
56     if( 0==m_size )return T();
57     else 
58     {
59         int save=m_front;
60         m_front=(m_front+1)%MAXN;
61         m_size--;
62         return head[save];
63     }
64 }
65 
66 template<typename T>
67 void Queue<T>::status()
68 {
69     cout<<"队尾  |  <<pushn";
70     for(int i=0;i<m_size;i++)
71     {
72         if(m_size-1==i)cout<<"队首  |"<<head[(m_rear-i-1)%MAXN]<<"| >>popn";
73         else cout<<"      |"<<head[(m_rear-i-1)%MAXN]<<"|n";
74     }
75 }

原文链接: https://www.cnblogs.com/backinfile/p/5821829.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/239715

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月13日 下午8:07
下一篇 2023年2月13日 下午8:08

相关推荐