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

队列 queue 的链表实现操作 -C++

2014-08-12 14:36 465 查看

队列(queue)

概念:只允许一端进行插入,另一端进行删除操作的线性表(像打饭的排队)

(先进先出:FIFO,插入的一端是队尾,删除的一端是队首)

和栈一样,队列也有数组实现和链表实现两种,两种实现都能给出快速的O(1)运行时间,区别在于链表实现指针域要占用空间,频繁的new和delete会消耗不少的时间开销,数组实现唯一的缺点是建立时要确定空间大小。

队列的数组实现和栈差不多,不同的是,栈用top做下标,队列用front和rear作为下标。

下面的程序,我使用C++ STL实现和根据单链表实现的简单队列程序。

#include<iostream>
#include<queue>
using namespace std;
typedef struct queueNode //与stack一样,同样单链表做基础
{
int data;
queueNode *next;
}node;
typedef struct //对单链表进行包装,增加两个指向node的指针
{			//可以看做是对单链表的头结点进行改造...........
node *frond,*rear;
int length;
}linkQueue;
linkQueue *initQueue()
{
linkQueue *p=new linkQueue;
p->rear=NULL;
p->frond=NULL;
p->length=0;
return p;
}
bool enQueue(linkQueue *pLinkQueue,int val)
{
node *pNode=new node;
if (pNode==NULL)
{
return false;
}
pNode->data=val;
pNode->next=NULL;
if (pLinkQueue->rear)  //如果链队列为非空,则插入尾部,否则,直接赋值给尾部
{
pLinkQueue->rear->next=pNode;          //注意此时只对plinkQueue的指针操作
pLinkQueue->rear=pNode;    //对plinkQueue所指向的Node操作
}
else
{
pLinkQueue->frond=pNode;
pLinkQueue->rear=pNode;          //注意此时只对plinkQueue的指针操作
}
pLinkQueue->length++;
return true;
}
bool deQueue(linkQueue *pLinkQueue,int *val)//参考:http://www.cppblog.com/cxiaojia/archive/2012/08/02/186033.html
{
if (pLinkQueue->length==0)
{
return false;
}
*val=pLinkQueue->frond->data;
node *pNode=pLinkQueue->frond;
pLinkQueue->frond=pLinkQueue->frond->next;
delete pNode;
pLinkQueue->length--;
return true;
}
int main()
{
queue<int> q;
for (int i=0;i<10;i++)
{
q.push(i);
}
while(!q.empty())
{
int val=q.front();
q.pop();
cout<<val<<' ';
}
cout<<endl;
cout<<"----------------------------------"<<endl;
linkQueue *linkQueue0=initQueue();
for (int i=0;i<10;i++)
{
enQueue(linkQueue0,i);
}
int val=0;
cout<<"the Length of the LinkQueue is:"<<linkQueue0->length<<endl;
for(int j=0;j<10;j++)
{
deQueue(linkQueue0,&val);
cout<<val<<' ';
}
cout<<endl;
return 0;
}



看着简单,自己动手写起来还是有点难度。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: