您的位置:首页 > 其它

环形顺序队列的实现

2017-02-22 11:27 435 查看
一、队列的定义

队列是一种特殊的线性表,线性表两端都可以进行插入删除,而队列只能在队头删除,队尾插入。插入元素称为入队,删除元素称为出队。

特点:

(1)队列只允许在队头插入,队尾删除;

(2)先入队的元素在对头,后入队的元素在队尾;

(3)队列遵循“先进先出”的原则。
图示:
  (1)普通队列



(2)环形队列



二、存储结构及实现
Queue.h
#pragma once
//环形顺序队列
#define SIZE 10
#define ElemType int

typedef struct Queue
{
ElemType elem[SIZE];//数据域
int front;//队头指针,队列中第一个元素的下标
int rear;//队尾指针,当前可以存放数据的下标
}Queue;

void InitQueue(Queue &pq);//初始化队列
bool Push(Queue &pq, int val);//入队
bool GetTop(Queue &pq, int *rtval);//获取队头的值,但不删除
bool Pop(Queue &pq);//出队
bool IsFull(Queue &pq);//判断对列为满
bool IsEmpty(Queue &pq);//判断对列为空
void Display(Queue &pq);//显示对列元素

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

void InitQueue(Queue &pq)//初始化队列
{
pq.front = pq.rear = 0;
}
bool Push(Queue &pq, int val)//入队
{
if (IsFull(pq))
{
return false;
}
pq.elem[pq.rear] = val;
pq.rear = (pq.rear + 1) % SIZE;
return true;
}
bool GetTop(Queue &pq, int *rtval)//获取队头的值,但不删除
{
if (IsEmpty(pq))
{
return false;
}
*rtval = pq.elem[pq.front];
return true;
}
bool Pop(Queue &pq)//出队
{
if (IsEmpty(pq))
{
return false;
}
pq.front = (p
4000
q.front + 1) % SIZE;
return true;
}
bool IsFull(Queue &pq)
{
return (pq.rear + 1) % SIZE == pq.front;
}
bool IsEmpty(Queue &pq)
{
return pq.rear == pq.front;
}

void Display(Queue &pq)
{
for (int i = pq.front; i < pq.rear; ++i)
{
cout << pq.elem[i] << " ";
}
cout << endl;
}
main.cpp
#include <iostream>
#include "Queue.h"
using namespace std;

int main()
{
Queue List;
InitQueue(List);
for (int i = 0; i < 10; ++i)
{
Push(List,i);
}
Display(List);
Pop(List);
Display(List);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: