队列(先进先出):所有的增加在表的一端进行,所有的删除都在表的另一端进行。
队头(front):第一个将从队列中删除的元素称为队头。
队尾(rear或tail):队列中的最后一个元素,即最近加入的一个元素称为队尾。
队列的实现:
- 头文件Queue.h
#include <iostream>
#include <cstdio>
#define MAXSIZE 10
using namespace std;
enum Error_code{
overflow, underflow, success
};
typedef char Queue_entry;
class Queue{
public:
//建立队列并将其初始化为空
Queue();
bool empty() const;
//如果队列有空间,则将元素添加到队尾
Error_code append(const Queue_entry & item);
//如果队列非空,则删除队头的元素
Error_code serve();
//如果队列非空,则队头的元素记为item
Error_code retrieve(Queue_entry & item) const;
private:
int rear, front;
int count;
Queue_entry entry[MAXSIZE];
};
- 具体函数实现Queue.cpp
思想:使用循环数组
Queue::Queue(){
count = 0;
rear = MAXSIZE - 1;
front = 0;
}
bool Queue::empty() const{
return count == 0;
}
Error_code Queue::append(const Queue_entry & item){
if(count >= MAXSIZE) return overflow;
count ++;
rear = ((rear + 1) == MAXSIZE) ? 0 : (rear + 1);
entry[rear] = item;
return success;
}
Error_code Queue::serve(){
if(count <= 0) return underflow;
count --;
front = ((front + 1) == MAXSIZE) ? 0 : (front + 1);
return success;
}
Error_code Queue::retrieve(Queue_entry & item) const{
if(count <= 0) return underflow;
item = entry[front];
return success;
}
补充的其它函数:
size()函数、clear()函数、serve_and_retrieve()函数
void Queue::size() const{
return count;
}
void Queue::clear(){
count = 0;
front = 0;
rear = MAXSIZE - 1;
}
Error_code Queue::serve_and_retrieve(Queue_entry & item){
if(count == 0) return underflow;
else{
count --;
item = entry[front];
front = ((front + 1) == MAXSIZE) ? 0 : (front + 1);
}
return success;
}