循环队列的顺序结构实现


  1 class Queue
  2 {
  3 public:
  4     Queue(int len = 10);
  5     Queue(const Queue& src);
  6     Queue& operator=(const Queue& src);
  7     ~Queue();
  8 
  9     void Push(int val);
 10     void Pop();
 11     int getHead();
 12 
 13     bool isEmpty();
 14     bool isFull();
 15     void show();
 16 private:
 17     int* _arr;
 18     int _head;
 19     int _tail;
 20     int _len;
 21 };
 22 
 23 Queue::Queue(int len) : _head(0), _tail(0)
 24 {
 25     if (len < 10)
 26     {
 27         _len = 10;
 28     }
 29     _len = len;
 30     _arr = new int[len];
 31 }
 32 
 33 Queue::Queue(const Queue&ob) :  _head(ob._head), _tail(ob._tail)
 34 {
 35     _arr = new int[ob._len];
 36     _len = ob._len;
 37     for (int j = _head; j != _tail; j = (j + 1) % _len)
 38     {
 39         _arr[j] = ob._arr[j];
 40     }
 41 }
 42 
 43 Queue& Queue::operator=(const Queue& src)
 44 {
 45     if (this == &src)
 46     {
 47         return *this;
 48     }
 49     if (_arr == nullptr)
 50     {
 51         delete[]_arr;
 52     }
 53     _arr = new int[src._len];
 54     _len = src._len;
 55     _head = src._head;
 56     _tail = src._tail;
 57     for (int j = _head; j != _tail; j = (j+1)%_len)
 58     {
 59         _arr[j] = src._arr[j];
 60     }
 61     return *this;
 62 
 63 }
 64 
 65 Queue::~Queue()
 66 {
 67     if(_arr )
 68     delete[]_arr;
 69     _arr = nullptr;
 70     _head = 0;
 71     _tail = 0;
 72     _len = 0;
 73 }
 74 bool Queue::isEmpty()
 75 {
 76     return _head == _tail;
 77 }
 78 
 79 bool Queue::isFull()
 80 {
 81     return (_tail + 1) % _len == _head;
 82 }
 83 
 84 void Queue::Push(int val)
 85 {
 86     if (!isFull())
 87     {
 88         _arr[_tail] = val;
 89         _tail = (_tail + 1) % _len;
 90     }     
 91 }
 92 
 93 void Queue::Pop()
 94 {
 95     if (!isEmpty())
 96     {
 97         _head = (_head + 1) % _len;
 98     }
 99 }
100 
101 int Queue::getHead()
102 {
103     if (!isEmpty())
104     {
105         return _arr[_head];
106     }
107 }
108 
109 void Queue::show()
110 {
111     for (int j = _head; j != _tail; j = (j + 1) % _len)
112         cout << j << " ";
113 }
114 
115 int main() {
116    
117     int arr[] = { 123,32,7,25,453,791,66,432,1245,9,770};
118     Queue q;
119     for (int j = 0; j < 9; ++j)
120     {
121         q.Push(j);
122     }
123     q.show();
124     cout << endl;
125     for (int j = 0; j < 4; ++j)
126     {
127         cout<<q.getHead()<<endl;
128         q.Pop();
129     }
130     q.show();
131     return 0;
132 
133 }


 
原文地址:https://www.cnblogs.com/dhhu007/p/13177957.html