1.頭檔案:
# include<iostream>
using namespace std;
struct LinkNode{ //自定義資料類型:結點
int date;
LinkNode* link;
LinkNode(LinkNode* ptr=NULL):link(ptr){}
LinkNode(const int x,LinkNode* ptr=NULL):date(x),link(ptr){}
};
class LinkedQueue{ //鍊式隊列
private:
LinkNode* front; //隊頭指針
LinkNode* rear; //隊尾指針
public:
LinkedQueue():front(NULL),rear(NULL){} //構造函數:構造空隊列
void makeEmpty(); //将表置空
~LinkedQueue(){ makeEmpty();} //析構函數:(*不能直接用delete清空全部存儲空間的析構函數往往需要調用另一個函數幫助清空)
bool EnQueue(int& x); //進隊函數
bool DeQueue(int& x); //出隊函數
bool getFront(int& x); //取隊頭
bool isEmpty(){ return (front==NULL)?true:false;} //判斷表空
int getSize(); //求隊列元素個數
friend ostream& operator<<(ostream& ostr,LinkedQueue& Q); //輸出運算符重載
};
2.源檔案:
# include<iostream>
# include"LinkedQueue.h"
using namespace std;
void LinkedQueue::makeEmpty(){
LinkNode* ptr;
while(isEmpty()==false){
ptr=front;
front=front->link;
delete ptr;
rear=NULL; //删除尾結點後尾指針需要置空
}
}
bool LinkedQueue::EnQueue(int& x){
if(isEmpty()){
front=rear=new LinkNode(x);
if(front==NULL) return false;
}
else{
rear->link=new LinkNode(x);
if(rear->link==NULL) return false;
rear=rear->link;
}
return true;
}
bool LinkedQueue::DeQueue(int& x){
if(isEmpty()) return false;
else{
x=front->date;
LinkNode* current=front;
front=front->link;
delete current;
}
return true;
}
bool LinkedQueue::getFront(int& x){
if(isEmpty()) return false;
else{
x=front->date;
return true;
}
}
int LinkedQueue::getSize(){
int count=0;
LinkNode* ptr=front;
while(ptr!=NULL){
count++;
ptr=ptr->link;
}
return count;
}
ostream& operator<<(ostream& ostr,LinkedQueue& Q){
ostr<<"隊列中有元素個數:"<<Q.getSize()<<endl;
LinkNode* current=Q.front;int i=0;
while(current!=NULL){
ostr<<++i<<":"<<current->date<<endl;
current=current->link;
}
return ostr;
}