循环队列中的pop()操作.我该如何移除物品呢?
pop() operation in Circular Queue. How do i actually remove the item?
我试图在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"。
您实际上不必删除任何内容。这是一个循环队列,你需要从queueFront
到queueBack
。在你的情况下,最初你的队列是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
。
相关文章:
- boost::进程间消息队列引发错误
- 如果我只是不访问queue_front节点的子节点,而是将它们推到队列中呢?还是BFS吗
- Android NDK传感器向事件队列报告奇怪的间隔
- C++优先级队列,按对象的唯一指针的特定方法升序排列
- 函数何时会在c++中包含stack_Unwind_Resume调用
- 按对象的特定方法按升序排列的C++优先级队列
- 使用2个键的cpp-stl::优先级队列排序不正确
- Python中的for循环与C++有何不同
- 当有分配器意识的容器被复制/移动时,反弹分配器是否被复制/移走
- 我是否需要在下一次转移时将所有权*转移回转移队列
- 在一个读写器队列中,我可以用volatile替换原子吗
- 为什么我的多线程作业队列崩溃
- 尝试将lambda函数放在队列中时出现一般分配器错误(可能是与unique_ptr有关的错误)
- 移除前面有空格的前2个字符串
- 使用"Task"函数指针队列定义作业管理器
- 系统.将数组移交给c#中动态加载的c++DLL时发生AccessViolationException
- 在c++队列中使用pop和visit实现线程安全
- 什么是堆栈?arrayStack ?arrayQueue ?堆栈队列 ?它们在C++上有何不同
- 循环队列中的pop()操作.我该如何移除物品呢?
- 如何将队列的前C++项移到后面?