您的位置:首页 > 其它

队列的基本操作

2015-11-28 11:59 351 查看
队列特性:先进先出(FIFO)——先进队列的元素先出队列。来源于我们生活中的队列(先排队的先办完事)。



队列有下面几个操作:

InitQueue()   初始化队列
EnQueue() 进队列
DeQueue() 出队列
QueLength( ) 队列元素个数
DestroyQueue( ) 销毁队列

队列可以由数组和链表两种形式实现队列操作;

下边是队两种实现的基本操作:

#include "stdafx.h"
#include<iostream>
using namespace std;

#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
#define OVERFLOW -2
#define INFEASIALE -1

typedef int status;
typedef int QElemType;

//链队列,需要带头节点
struct LQnode{
QElemType data;
struct LQnode *next;
};

typedef struct{
LQnode *front;
LQnode *rear;
}LinkQueue;

status InitQueue(LinkQueue &q)
{
LQnode *s = new LQnode;
s->next = NULL;
q.front = q.rear = s;
return OK;
}
status GetFront(LinkQueue q, QElemType &e)
{
if (q.front == q.rear)
{
return ERROR;
}
e = q.front->next->data;
return OK;
}
status DestroyQueue(LinkQueue &q)
{
while (q.front)
{
q.rear = q.front->next;
delete q.front;
q.front = q.rear;
}
return OK;
}
status EnQueue(LinkQueue &q, QElemType x)
{
LQnode *s = new LQnode;
s->data = x;
s->next = NULL;
q.rear->next = s;
q.rear = s;
return OK;
}
status DeQueue(LinkQueue &q, QElemType &e)
{
if (q.front == q.rear)
{
return ERROR;
}
e = q.front->next->data;
LQnode *s = q.front->next;
q.front->next = q.front->next->next;
if (q.rear == s)//这里是因为若队列只有一个元素时,出队一个元素后,尾指针应该指向q.front,
{              //若不修改,则会变成悬垂指针
q.rear = q.front;
}
delete s;
return OK;
}
//循环队列,判断队列空和队列满时都有front == rear,需要区分队列空和队列满的状态
//方法1:另设一个标志位以区别“空”和“满”
//方法2:少用一个元素空间,约定以队列头指针在队列尾指针的下一位置(环状)上作为队列满状态
//下面用第二种方法
#define MAXQSIZE 10
typedef struct{
QElemType *base;
int front;
int rear;
}SqQueue;
status Initqueue(SqQueue &q)
{
q.base = new QElemType[MAXQSIZE];
if (!q.base)
{
exit(OVERFLOW);
}
q.front = q.rear = 0;
return OK;
}
int QueLength(SqQueue q)
{
return (q.rear - q.front + MAXQSIZE) % MAXQSIZE;
}
status EnQueue(SqQueue &q, QElemType x)
{
if ((q.rear + 1) % MAXQSIZE == q.front)
{
return ERROR;
}
q.base[q.rear] = x;
q.rear = (q.rear + 1) % MAXQSIZE;
return OK;
}
status DeQueue(SqQueue &q, QElemType &e)
{
if (q.front == q.rear)
{
return ERROR;
}
e = q.base[q.front];
q.front = (q.front + 1) % MAXQSIZE;
return OK;
}
int _tmain(int argc, _TCHAR* argv[])
{
LinkQueue q;
InitQueue(q);
SqQueue s;
Initqueue(s);
for (int i = 0; i < 10; i++)
{
EnQueue(q, i);
EnQueue(s, i+1);
}
int e;
GetFront(q, e);
cout << "链队的头元素为:" << endl;
cout << e << endl;;
cout << "链队全部出队为:" << endl;
for (int j = 0; j < 10; j++)
{
DeQueue(q, e);
cout << e << ' ';
}
cout << endl;
cout << "循环队列现在长度为:" << endl;
int count = QueLength(s);
cout << count << endl;
cout << "循环队列全部出队为:" << endl;
for (int k = 0; k < count; k++)
{
DeQueue(s, e);
cout << e << ' ';
}
system("pause");
return 0;
}



队列的一个使用例子为:离散时间模拟(比如银行业务处理)!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: