【发布时间】: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() 实际删除元素
-
“实际删除一个项目”是什么意思?一个项目被非实际删除意味着什么?