c++ - 同一个数组上的堆栈和队列操作

标签 c++ algorithm

我一直在思考程序逻辑,但我无法对我的问题下结论。

在这里,我实现了对固定数组的栈和队列操作。

int A[1000];
int size=1000;

int top;

int front;
int rear;

bool StackIsEmpty()
{
    return (top==0);
}

bool StackPush( int x )
{
    if ( top >= size ) return false;
    A[top++] = x;
    return true;
}

int StackTop( )
{
    return A[top-1];
}

bool StackPop()
{
    if ( top <= 0 ) return false;
    A[--top] = 0;
    return true;
}

bool QueueIsEmpty()
{
    return (front==rear);
}

bool QueuePush( int x )
{
    if ( rear >= size ) return false;
    A[rear++] = x;
    return true;
}

int QueueFront( )
{
    return A[front];
}

bool QueuePop()
{
    if ( front >= rear ) return false;
    A[front++] = 0;
    return true;
}

假定(或明显)堆栈底部和队列前端指向相同位置,反之亦然(堆栈顶部与队列后端指向相同位置)。

例如,整数 1 和 2 按书写顺序在一个数组中。如果我调用 StackPop(),整数 2 将被弹出,如果我调用 QueuePop(),整数 1 将被弹出。

我的问题是我不知道如果我在同一个数组上同时执行堆栈和队列操作会发生什么。上面的例子很容易计算,因为只涉及两个值。但是,如果涉及的值超过 2 个怎么办?

例如,如果我调用

StackPush(1);
QueuePush(2);
QueuePush(4);
StackPop();
StackPush(5);
QueuePop();

从最后的数组中按底部(前面)的顺序返回什么值?

我知道如果我编写一个程序,我会很快得到答复。但我问这个的原因是因为我想听到一个人的逻辑解释,而不是计算机。

添加: 对于第二个例子,我有 4 个候选人。 25 12 24 45 或者这里根本没有答案。

最佳答案

为什么要在同一个数组上实现这些?如果您这样做,一个结构的元素可能会覆盖另一个结构的元素。

你基本上有(类似的东西)一个deque然而,却很难手动运行您的程序,因为您对这两个数据结构有不同的指针,但对它们只有一个数组。

It is presumed(or obvious) that the bottom of the stack and the front of the queue is pointing at the same location, and vice versa(top of the stack points the same location as rear of the queue).

好吧,在这种情况下可以,但是您应该只使用双端队列,它在这种假设下不起作用。或者对队列和堆栈使用不同的 vector 。

一般来说,人类所做的正是计算机的工作方式。只需让您的程序在每次操作后打印A 的内容,这应该是合乎逻辑的。

关于c++ - 同一个数组上的堆栈和队列操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2662896/

相关文章:

java - 省略 for 循环中的第一个参数

c++ - 使用回调来自定义类而不是子类化

c++ - GTK最大化Form c++

c++ - 线弯曲的简单算法

python - 关于加快旅行商问题的动态规划解决方案的建议?

algorithm - 从一组有限的图 block 中找到最大的平方(近似值)

Python - 低效的空间距离计算(如何加速)

将列转换为 2D vector 的 C++ 文本文件

c++ - 在 winapi CALLBACK 函数上返回 FALSE 时出现意外行为(跳过循环?)

python - Python 采样模块