【问题标题】:pop() operation in Circular Queue. How do i actually remove the item?循环队列中的 pop() 操作。我如何实际删除该项目?
【发布时间】:2013-06-02 10:32:57
【问题描述】:

我正在尝试使用 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;
  }
 }

我在运行时得到以下输出:

0 0 0 0 0 0 0 0 1 删除。 1 2 3 5 0 0 0 0

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

谢谢

【问题讨论】:

  • 你为什么不实现一个真正的类而不是使用全局变量?
  • 如果要查看队列的内容,为什么不只从queueFront迭代到queueBack呢?
  • 如果你不能使用除常量数组之外的任何东西,你只能用一个已知的值来代替旧的“空”,如果你只处理自然整数,就可以使用 -1。跨度>
  • @segfolt 我知道使用 Class 的析构函数是正确的方法。但是我想知道给定一个数组,如何使用 pop() 实际删除元素
  • “实际删除一个项目”是什么意思?一个项目被非实际删除意味着什么?

标签: c++ queue


【解决方案1】:

鉴于 pop() 在确定队列为空后仍会更改队列,因此对 #2 的回答为“否”。

【讨论】:

    【解决方案2】:

    您实际上不必删除任何内容。这是一个循环队列,你需要从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。我建议你为队列实现一个打印功能,这样事情可以得到简化,或者至少你可以看到队列的内容而不是数组的内容。

    就实现而言,它稍微偏离了轨道,因为您可以获得最大值。队列中有 7 个元素,而不是 8 个(如您所料)。这是因为您在数组中的位置queueBack 插入时检查((queueBack + 1 ) % arrayLength) == queueFront

    【讨论】:

      猜你喜欢
      • 2014-08-12
      • 1970-01-01
      • 2014-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-03
      • 2011-01-04
      • 1970-01-01
      相关资源
      最近更新 更多