我正在尝试在 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. 我如何实际删除 pop() 操作中的项目? 2. 我的实现是否正确?
谢谢
最佳答案
鉴于 pop() 在确定队列为空后仍会更改队列,因此对 #2 的回答是“否”。
关于c++ - 循环队列中的 pop() 操作。我如何真正删除该项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16881930/