逻辑线性结构,先进先出FIFO;队列是两端出入数据,堆栈是单端出入数据;
入队列在队尾,出队列在队首;
头文件
Queue.h
#ifndef _QUEUE_H_
#define _QUEUE_H_
typedef unsigned char boolean;
#define DEFAULT 10
#define IN 1
#define OUT 0
template<typename Type>
class Queue{
public:
Queue(size_t sz = 0){
count = sz > DEFAULT ? sz : DEFAULT;
data = new Type[count];
head = tail = 0;
lastAction = OUT;
}
Queue(const Queue &t);
Queue& operator=(const Queue &t);
~Queue(){
delete []data;
}
public:
bool isEmpty(){
return lastAction == OUT && head == tail;
}
bool isFull(){
return lastAction == IN && head == tail;
}
bool in(const Type &x);
bool out(Type *value);
bool getHead(Type *value);
void lookAllQueueElem()const;
private:
Type *data;
int count;
int head;
int tail;
boolean lastAction;
};
template<typename Type>
bool Queue<Type>::in(const Type &x){
if(isFull()){
return false;
}
data[tail] = x;
tail = (tail+1)%count;
lastAction = IN;
return true;
}
template<typename Type>
bool Queue<Type>::out(Type *value){
if(isEmpty()){
return false;
}
*value = data[head];
head = (head+1)%count;
lastAction = OUT;
return true;
}
template<typename Type>
bool Queue<Type>::getHead(Type *value){
if(isEmpty()){
return false;
}
*value = data[head];
return true;
}
template<typename Type>
void Queue<Type>::lookAllQueueElem()const{
int i;
if(head > tail){
for(i = head; i < count; i++){
cout<<data[i]<<" ";
}
for(i = 0; i < tail; i++){
cout<<data[i]<<" ";
}
}
for(i = head; i < tail; i++){
cout<<data[i]<<" ";
}
cout<<endl;
}
#endif
源文件
Queue.cpp
#include<iostream>
#include<stdlib.h>
#include"Queue.h"
using namespace std;
int main()
{
Queue<int> qu;
int value;
qu.in(10);
qu.in(20);
qu.in(30);
qu.in(40);
qu.in(50);
qu.in(60);
qu.in(70);
qu.in(80);
qu.in(90);
qu.lookAllQueueElem();
qu.getHead(&value);
cout<<value<<endl;
qu.out(&value);
cout<<value<<endl;
qu.lookAllQueueElem();
system("pause");
return 0;
}