C++队列数组实现

来源:互联网 发布:非嵌入式软件即征即退 编辑:程序博客网 时间:2024/05/16 19:21

#include<iostream>
#include<stdlib.h>
using namespace std;
typedef int T;
class Queue
{
 T a[5];
 int b, n;//队首位置和有效元素个数
public:
 Queue() :b(0), n(0){}
 Queue& push(const T& d)
 {
  if (full())
  {
   cout << "满!" << endl;
   system("pause");
   exit(1);
  }
  a[(b + n++) % 5] = d;
  return *this;
 }
 T pop()
 {
  if (empty())
  {
   cout << "空!" << endl;
   system("pause");
   exit(1);
  }
  --n;
  return a[b++ % 5];
 }
 const T& front()const
 {
  return a[b % 5];
 }
 const T& back()const
 {
  return a[(b + n - 1) % 5];
 }
 int size()const
 {
  return n;
 }
 void clear()
 {
  b = n = 0;
 }
 bool empty()const
 {
  return n == 0;
 }
 bool full()const
 {
  return n == 5;
 }
};
int main()
{
 Queue q;
 q.push(1).push(2).push(3).push(4);
 cout << q.front() << endl;
 cout << q.back() << endl;

 cin.get();
 return 0;
}


0 0
原创粉丝点击