C++实现队列

来源:互联网 发布:中国第一 知乎 编辑:程序博客网 时间:2024/06/11 01:58

像栈一样,队列(queue)也是表。然而,使用队列时插入在一端进行而删除则在另一端进行,也就是先进先出(FIFO)。队列的基本操作是EnQueue(入队),它是在表的末端(叫做队尾(rear))插入一个元素;还有DeQueue(出队),它是删除(或返回)在表的开头(叫做队头(front))的元素。

 

同样,队列也可以由链表或数组实现,特点分析如下:

链表:不需要设定空间大小,也不会浪费空间;插入或删除时需要动态分配或删除内存,比较耗时;不支持随机存取;

数组:需要预知需要空间的大小,会造成空间浪费或不够用;插入或删除不需要动态分配或删除内存,耗时很小;支持随机存取。

 

另外,队列又有链式队列和循环队列两种。本文给出用单链表实现的链式队列(循环队列可类似地用循环列表实现)和用数组实现的循环队列(当数组空间够大时,链式队列和循环队列是一样的)。



//C++实现队列

#include<iostream>
using namespace std;
template<class T>
struct node
{
T data;
node<T>* next;
};
template<class T>
class Queue
{
public:
Queue();
void push(T data1);
void pop();
void display();
~Queue();
private:
node<T>* head;
};
template<class T>  Queue<T>::Queue()
{
head=new node<T>;
head->next=NULL;
head->data=NULL;
}
template<class T> void Queue<T>::push(T data1)
{
node<T>*p=new node<T>;
node<T>*q=new node<T>;
q=head;
p->data=data1;
p->next=NULL;
if(NULL==head->next)
head->next=p;
else
{
while(NULL!=q->next)
q=q->next;
q->next=p;
}
}


template<class T> void Queue<T>::pop()
{
if(NULL==head->next)
cout<<"队列是空的"<<endl;
else
{
cout<<"出队列的元素"<<endl;
cout<<head->next->data<<endl;
head=head->next;
}
}


template<class T> void Queue<T>::display()
{
node<T>*p=new node<T>;
p=head;
if(NULL!=p->next)
{
while(NULL!=p->next)
{
cout<<p->next->data<<" ";
p=p->next;
}
}
else
cout<<"队列是空的"<<endl;
cout<<endl;
}



template<class T>  Queue<T>::~Queue()
{
node<T>*p;
while(NULL!=head->next)
{
p=head;
head=head->next;
delete p;
p=NULL;
}
delete head;
head=NULL;
}


int main()
{
Queue<int>queue1;
Queue<char>queue2;
queue1.push(12);
queue1.push(18);
queue1.push(8);
queue1.push(9);
queue1.push(6);
queue1.display();
queue1.pop();
queue1.pop();
queue2.push('a');
queue2.push('b');
queue2.push('f');
queue2.push('g');
queue2.display();
queue2.pop();
queue2.pop();
return 0;
}
0 0
原创粉丝点击