您的位置:首页 > 编程语言 > C语言/C++

c++实现队列操作(建对、入队、出对)

2010-06-25 15:20 281 查看
template<class T>
class Node/*定义节点的头文件,文件名为:b.h   */
{
public:
int data;
Node<T> *next;
Node()
{
this->next=NULL;
}
Node(int data,Node<T> *next=NULL)
{
this->data=data;
this->next=next;
}
};

#include<iostream.h>
#include "b.h"
template<class T>/*主程序,queue.cpp*/
class Queue
{
private:
Node<T> *front,*rear;
public:
Queue();
~Queue();
bool isEmpty();
void append(int x);
int get();
};
template<class T>
Queue<T>::Queue()
{
front=rear=NULL;
}
template<class T>
Queue<T>::~Queue()
{
Node<T> *p=front,*q;
while(p!=NULL)
{
q=p;
p=p->next;
delete q;
}
front=rear=NULL;
}
template<class T>
bool Queue<T>::isEmpty()
{
return front==NULL&&rear==NULL;
}
template<class T>
void Queue<T>::append(int x)
{
Node<T> *q=new Node<T>(x);
if(isEmpty())
front=q;
else
rear->next=q;
rear=q;

}
template<class T>
int Queue<T>::get()
{
if(!isEmpty())
{
int x=front->data;
Node<T> *p=front;
front=front->next;
delete p;
if(front==NULL)
rear=NULL;
return x;
}
throw "空队列!";
}
int main()
{
Queue<int> Q;
int x,y,n,i;
cout<<"请输入队列长度:"<<endl;
cin>>n;
cout<<"请输入各元素的值:"<<endl;
for(i=0;i<n;i++)
{
cin>>x;
Q.append(x);
}
cout<<"对头元素是:"<<endl;
y=Q.get();
cout<<y;
return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐