队列实现C++

Queue realisation C++

本文关键字:C++ 实现 队列      更新时间:2023-10-16

我对队列的实现以一种奇怪的方式工作:当我将新元素排队时 - 一切都正确,但是当我开始取消排队时 - 它删除了最后一个添加的元素,尽管此时我的头是 1 并且尾巴更大。C++索引的特点是什么?为什么它的行为是这样的?这是我的完整代码:https://hastebin.com/odibusacuk.cpp

class Queue{
public:
int head=1;
int tail=1;
int q[MAX];
int Queue::enqueue(int x){
    if (isFull()){
        return 0;}
    else {
        q[tail]=x;
       cout << tail << " here is a tailn";
        if (tail==sizeof(q)){
            cout << tail << " this is tailn" ;
            tail=1;}
        else {
            tail=tail+1;
            }
        return x;
        }
}
int Queue::dequeue(){
if(isEmpty()){
    cout << " the queue is emptyn";
    return 0;}
else {
    int x=q[head];
    if (head==sizeof(q)){
        head=1;}
    else {
        head=head++;
return x;}
    }
return 0;
}

你遇到的问题是因为当你做类似的事情时

cout << k.enqueue(4) << " " << k.enqueue(9)  << ' ' << k.enqueue(6) << " " << k.enqueue(3) << " enqueuedn ";

没有指定这些函数的调用顺序。在您的示例中,从右到左调用它们。这意味着您的队列实际上是

{ 0, 3, 6, 9, 4 }
0

在那里,因为您跳过元素 0 并直接转到元素 1。您的头指向 1,因此您将取消排队 3。

您可以在此处阅读更多内容。