帶鏈佇列類

小許發表於2012-08-06

帶鏈佇列類:檔名 linked_Queue.h

#include <iostream>
using namespace std;
template <class T>
struct node
{
    T d;
	node *next;
};
template <class T>
class linked_Queue
{
private:
	node<T> *front,*rear;
public:
	linked_Queue();
	void prt_linked_Queue();
	int flag_linked_Queue();
	void ins_linked_Queue(T);
	T del_linked_Queue();

};
template <class T>
linked_Queue<T>::linked_Queue()
{
	front=NULL;
	rear=NULL;
	return;
}
template <class T>
void linked_Queue<T>::prt_linked_Queue()
{
	
	node<T> *p;
	p=front;
	if(p==NULL)
	{
		cout<<"佇列為空"<<endl;
		return;
	}
	do 
	{
		cout<<p->d<<endl;
		p=p->next;

	} while (p!=NULL);
	return;
}
template <class T>
int linked_Queue<T>::flag_linked_Queue()
{
	if(NULL==front)
	{
		cout<<"佇列為空"<<endl;
		return 0;
	}
	return 1;
}
template <class T>
void linked_Queue<T>::ins_linked_Queue(T b)
{
	node<T> *p;
	p=new node<T>;
	p->d=b;
	p->next=NULL;
	if(rear==NULL)
		front=p;
	else
		rear->next=p;
	rear=p;
	return;
}
template <class T>
T linked_Queue<T>::del_linked_Queue()
{
	T y;
	node<T> *q;
	if(front==NULL)
	{
		cout<<"空隊"<<endl;
		return 0;
	}
	y=front->d;
	q=front;
	front=q->next;
	delete q;
	if(front==NULL)rear=NULL;
	return(y);
}


應用例項:

#include "linked_Queue.h"
#include <stdlib.h>
int main()
{
	linked_Queue<int> q;
	q.ins_linked_Queue(50);
	q.ins_linked_Queue(60);
	q.ins_linked_Queue(70);
	q.ins_linked_Queue(80);
	q.ins_linked_Queue(90);
	q.ins_linked_Queue(100);
	cout<<"輸出帶鏈佇列中的元素"<<endl;
	q.prt_linked_Queue();
	if(q.flag_linked_Queue())
		cout<<"輸出退隊元素:"<<q.del_linked_Queue()<<endl;
	if(q.flag_linked_Queue())
		cout<<"輸出退隊元素:"<<q.del_linked_Queue()<<endl;
	if(q.flag_linked_Queue())
		cout<<"輸出退隊元素:"<<q.del_linked_Queue()<<endl;
	
	cout<<"再次輸出帶鏈佇列中的元素"<<endl;
	q.prt_linked_Queue();
	system("pause");
	return 0;

}


實驗結果:

相關文章