这是我卡在下面的试卷中的一个问题,虽然我无法完成我已经完成了一些,但我已经附上了问题。
问题:
使用堆栈和队列类的以下类定义编写一个模板化函数 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/