循环队列中的pop()操作.我该如何移除物品呢?

pop() operation in Circular Queue. How do i actually remove the item?

本文关键字:何移 队列 pop 操作 循环      更新时间:2023-10-16

我试图在c++中使用数组实现一个简单的循环队列。下面是我的代码。

#include <iostream>
int  pop();
void push(int );
const int arrayLength = 8;
int inputArray[arrayLength] = {0};
int queueFront=0,queueBack=0;
void push(int theElement)
{
  //Check if the push causes queue to overflow
     if  (((queueBack + 1 ) % arrayLength) == queueFront)
 {
     std::cout<<"Queue is full."<<std::endl;
     return ;
 }
 inputArray[queueBack] = theElement;
     queueBack = (queueBack + 1) % arrayLength;
}

 int pop()
 {
   //Check if queue  is already empty
   if ( queueFront == queueBack )
   {
    std::cout<<"Queue is empty."<<std::endl;
   }
       std::cout<<inputArray[queueFront]<<" removed."<<std::endl;
   queueFront = (queueFront + 1 ) % arrayLength;

 }
int main()
{
  for ( int i =0; i < arrayLength; ++i)
  {
      std::cout<<inputArray[i]<<std::endl;
  }
  push(1);
  push(2);
  push(3);
  pop();
  push(5);
      //printing arrayelements
  for ( int i =0; i < arrayLength; ++i)
  {
    std::cout<<inputArray[i]<<std::endl;
  }
 }

当我运行时,我得到以下输出:

000000001删除。123.50000

问题1:1. 我如何在pop()操作中实际删除项目?2. 我的实现是否正确?

谢谢

假设pop()在确定队列为空后仍然改变队列,那么对#2的回答是"no"。

您实际上不必删除任何内容。这是一个循环队列,你需要从queueFrontqueueBack。在你的情况下,最初你的队列是1 2 3,后来它变成了2 3 5,但数组的内容是1 2 3 0 0 0 0 0早些时候,后来在你弹出它们保持不变,因为你已经移动了queueFront的位置。同样,当稍后修改队列时,通过压入5,数组的内容变为1 2 3 5 0 0 0 0。我建议你为队列实现一个print函数,这样事情就可以得到简化,或者至少你可以看到你的队列的内容,而不是数组的内容。

就实现而言,它稍微偏离了轨道,因为您可以获得最大值。队列中的7个元素,而不是8个(如您所期望的)。这是因为当您在数组

中插入位置queueBack时检查((queueBack + 1 ) % arrayLength) == queueFront