队列基本操作
队列是一种元素先进先出(FIFO)的线性结构,与栈不同的是,队列在队尾插入元素,在队首删除元素。这里我们实现的是循环队列,以防止“假上溢”浪费空间。
1 //队列基本操作 2 template <typename Type> class Queue { 3 private: 4 Type *data; 5 int head, tail, size, count; 6 public: 7 Queue(int size_input) { 8 data = new Type[size_input]; 9 size = size_input; 10 head = 0; 11 tail = -1; 12 count = 0; 13 } 14 ~Queue() { 15 delete[] data; 16 } 17 bool push(Type element) { 18 if (count >= size) { 19 return false; 20 } 21 tail = (tail + 1) % size; 22 data[tail] = element; 23 count++; 24 return true; 25 } 26 //要先确定队列不为空 27 void output() { 28 int i = head; 29 //用do-while是因为有可能head就在tail后一位 30 //(tail+1)%size是队尾后面一个位置 31 do { 32 cout << data[i] << " "; 33 i = (i + 1) % size; 34 } while(i != (tail + 1) % size); 35 cout << endl; 36 } 37 //要先确定队列不为空 38 Type front() { 39 return data[head]; 40 } 41 //要先确定队列不为空 42 void pop() { 43 head=(head+1)%size; 44 count--; 45 } 46 bool empty() { 47 return count==0; 48 } 49 };