c++ - c++中队列的反转

标签 c++ stack queue

这是我卡在下面的试卷中的一个问题,虽然我无法完成我已经完成了一些,但我已经附上了问题。

问题:

使用堆栈和队列类的以下类定义编写一个模板化函数 reverseQueue(?),它将指向队列的指针作为参数并使用堆栈对象(或指向堆栈对象的指针)来反转给定的队列。对 reverseQueue 的函数调用应该反转作为参数传递的队列数据。 [提示:只需在您的 reverseQueue(?) 函数中调用下面给出的适当方法。您不必为下面给出的堆栈和队列类/方法编写实现代码。只需阅读每种方法的作用并根据需要使用它们即可。]

template <class T>
struct NODE {
    NODE<T> *pNext;
    T Data;
};

template <class T>
class stack{
    private:
       NODE<T> * top;

    public:
       stack();
       ~stack();
       void push (T data); //pushes a new node with data type //T in a stack
       bool pop (T &data); //pops out the top most node from //the stack
       void printStack(); //prints all elements of a stack
};

template <class T>
class queue {
    private:
        NODE<T> * front;
        NODE<T> * tail;
    public:
        queue ();
        ~queue();
        bool dequeue ( T & data); //removes first node from //a queue
        bool enqueue (T val); //appends a new node in a //queue
};

我的回答不完整,因为我无法继续下面是我所做的一切的回答

template <class T>
void reverseQueue(queue <T> *ptr){
    stack <T> *stackptr= new stack<T>;
    T temp;
    while(ptr->front !=NULL){

        temp=ptr->Data;
        ptr->dequee(ptr->Data);
        stackptr->push(temp);

     }

    // incomplete code
} 

如果有人能给出答案那就太好了

最佳答案

假设输入队列看起来像

 1    2    3    4
 ^              ^
front           back

如果我们从中取出项目,我们将得到 1、2、3、4。

现在假设我们在将这些项目出队时将它们压入堆栈。
它看起来像这样:

4  <- top
3
2
1  <- bottom

如果我们弹出这些,我们将得到 4、3、2、1。

现在,如果我们在从堆栈中弹出它们时将它们放入队列中,我们将得到

 4    3    2    1
 ^              ^
front           back

这是原始队列的反向。

应该这样做:

template <class T>
void reverseQueue(queue <T> *q){
    stack <T> s;
    T temp;
    // First build a stack (LIFO queue) from the (FIFO) queue.
    while (q->dequeue(temp))
    {
        s.push(temp);
    }
    // The first item in the queue is now at the bottom of the stack.
    // The last item is at the top.
    // The queue is empty.

    // If we enqueue them again they will be reversed.
    while (s.pop(temp))
    {
        q->enqueue(temp);
    }
} 

关于c++ - c++中队列的反转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26875730/

相关文章:

c# - 为 C++ DLL 实现回调 C# 函数

c++ - 使用 EDSDK 录制视频 (Canon T3)

c# - 值类型变量是否违反栈的LIFO性质

python - 如何将队列引用传递给 pool.map_async() 管理的函数?

php - 使用多个数据库运行 laravel 队列

c++ - 如果测试程序崩溃,Valgrind Reports 是否可信

c++ - 读取输入文件,最快的方式可能吗?

r - 在 `geom_hline` 图中设置 `geom_bar` 的长度

c# - 在 C# 中使用 ref 参数在堆栈上会发生什么?

java - 将运算符从 double 转换回 char 后,如何使用它?