【数据结构】循环队列理解及练习



最近对循环队列进行了深入了解,根据自己的理解用AI画了下面的示意图,并对其要点进行了归纳。如下所示:

 

下面是书上的习题,设计一个可以在队头和队尾进行入队、出队的队列,算是循环队列的练习升级版,代码如下:

// ConsoleApplication1.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<iostream>
using namespace std;
const int  MAXSIZE = 100;//循环队列长度,可存储的最大数据个数为MAXSIZE-1
typedef struct cycQueue{
 int data[MAXSIZE];
 int front, rear;
}cycQueue;//数据类型定义

void initQueue(cycQueue  *& Q)//使用指针的引用
{
 Q = (cycQueue*)malloc(sizeof(cycQueue));
 Q->front = Q->rear=0;
}
int empty(cycQueue* Q)
{
 if (Q->front == Q->rear)
  return 1;
 else
  return 0;
}
int enQueue_f(cycQueue * Q, int x)//从队头入队
{
 if ((Q->front - 1 + MAXSIZE) % MAXSIZE == Q->rear)//判断队是否为满
  return 0;
 else
 {
  Q->data[Q->front] = x;//将x赋值给当前front指向的地址
  Q->front = (Q->front - 1 + MAXSIZE) % MAXSIZE;//将front指向下一个front
  return 1;
 }
}
int enQueue_r(cycQueue*Q, int x)//从队尾入队
{
 if ((Q->rear + 1) % MAXSIZE == Q->front)//判断队是否为满
  return 0;
 else
 {
  Q->data[(Q->rear + 1) % MAXSIZE] = x;//将x赋值给当前rear的下一个位置
  Q->rear = (Q->rear + 1) % MAXSIZE;
  return 1;
 }
}
int deQueue_f(cycQueue*Q, int &x)//从队头出队
{
 if (Q->rear == Q->front)//判断队是否为空
  return 0;
 else
 {
  x = Q->data[(Q->front + 1) % MAXSIZE];//将当前front指向的下一个位置的值赋给x,注:front没有存储有用值
  Q->front = (Q->front + 1) % MAXSIZE;//将front往前移动一位
  return 1;
 }
}
int deQueue_r(cycQueue*Q, int&x)//从队尾出队
{
 if (Q->rear == Q->front)//判断队列是否为空
  return 0;
 else
 {
  x = Q->data[Q->rear];//将当前队尾元素赋值给x
  Q->rear = (Q->rear - 1 + MAXSIZE) % MAXSIZE;//将当前队尾后移一位
  return 1;
 }
}

//以下是测试函数
int _tmain(int argc, _TCHAR* argv[])
{
 cycQueue * Q;
 int x;
 initQueue(Q);

 //1、头插法入队、出队,功能类似栈
 for (int i = 0; i < 10; i++)
  enQueue_f(Q, i);
 while (!empty(Q))
 {
  deQueue_f(Q, x);
  cout << x << endl;
 }
 cout << "==============================\n";
 //2、尾插法入队、出队,功能类似栈
 for (int i = 0; i < 10; i++)
  enQueue_r(Q, i);
 while (!empty(Q))
 {
  deQueue_r(Q, x);
  cout << x << endl;
 }
 cout << "==============================\n";
 //3、头入队,尾出队
 for (int i = 0; i < 10; i++)
  enQueue_f(Q, i);
 while (!empty(Q))
 {
  deQueue_r(Q, x);
  cout << x << endl;
 }
 cout << "==============================\n";
 //4、尾出队,头入队
 for (int i = 0; i < 10; i++)
  enQueue_r(Q, i);
 while (!empty(Q))
 {
  deQueue_f(Q, x);
  cout << x << endl;
 }
 return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章