#ifndef LINKEDQUEUE_H
#define LINKEDQUEUE_H
#include<iostream>
#include"../T2/LinkedList.h"
#include"Queue.h"
using namespace std;
template<typename T>
class LinkedQueue:public Queue<T>{
public:
LinkedQueue():rear(NULL),front(NULL){}
~LinkedQueue(){makeEmpty();}
bool EnQueue(const T &x);
bool DeQueue(T &x);
bool getFront(T &x);
void makeEmpty();
bool IsEmpty() const;
bool IsFull() const{return false;}
int getSize() const;
friend ostream& operator<<(ostream& os,LinkedQueue& queue){
LinkNode<T> *current = queue.front;
while(NULL!=current){
os << current->data << " ";
current = current->link;
}
os << endl;
return os;
}
protected:
LinkNode<T> *front,*rear;
};
#endif // LINKEDQUEUE_H
LinkedQueue.cpp
#include"LinkedQueue.h"
template<typename T>
bool LinkedQueue<T>::EnQueue(const T &x)
{
if(IsEmpty()){
front = rear = new LinkNode<T>(x);
if(NULL==front)
return false;
}else{
rear->link = new LinkNode<T>(x);
if(NULL==rear->link)
return false;
rear = rear->link;
}
return true;
}
template<typename T>
bool LinkedQueue<T>::DeQueue(T &x)
{
if(IsEmpty()){
return false;
}
LinkNode<T>* del = front;
x = del->data;
front = front->link;
delete del;
return true;
}
template<typename T>
bool LinkedQueue<T>::getFront(T &x)
{
if(IsEmpty()){
return false;
}
x = front->data;
return true;
}
template<typename T>
void LinkedQueue<T>::makeEmpty()
{
LinkNode<T> *del;
while(front!=NULL){
del = front;
front = front->link;
delete del;
}
}
template<typename T>
bool LinkedQueue<T>::IsEmpty() const
{
return front==NULL?true:false;
}
template<typename T>
int LinkedQueue<T>::getSize() const
{
LinkNode<T> *current = front;
int i = 0;
while(NULL!=current){
i++;
current = current->link;
}
return i;
}
int main()
{
LinkedQueue<int> queue;
int num=0;
for(int i=0;i<10;++i){
num++;
queue.EnQueue(num);
}
cout << queue;
for(int j=1;j<5;++j){
queue.DeQueue(num);
}
cout << queue;
queue.getFront(num);
cout << "front:" << num << ",size:" << queue.getSize() << endl;
}
1 2 3 4 5 6 7 8 9 10
5 6 7 8 9 10
front:5,size:6