【问题标题】:Error in using swap() STL while implementing Queue using two Stacks使用两个堆栈实现队列时使用 swap() STL 时出错
【发布时间】:2021-10-06 10:50:21
【问题描述】:

我试图使用两个堆栈来实现类队列,但我发现了一个错误。如果我交换两个堆栈(在弹出和前端操作之后),使用 STL 的 swap() 操作,我得到错误的答案,但是当我使用静态代码交换两个堆栈时,我得到正确的答案。 请让我知道到底发生了什么。

#include <bits/stdc++.h>
using namespace std;
template<typename T>
class Queue{
    stack<T> A;//non empty stack
    stack<T> B;
    public:
    void push(T x){//O(1)
        A.push(x);
    };
    void pop(){//O(n)
        if(A.empty()) return;
        while(A.size()>1){
            T element=A.top();
            A.pop();
            B.push(element);
        }
        //1 element remaining in A
        A.pop();
        //swap(A,B);//so that A is the non empty stack
        //using swap() in this case was giving wrong answer

        while(!B.empty()){
            T element=B.top();
            B.pop();
            A.push(element);
        }
    };
    int front(){//O(n)
        while(A.size()>1){
            T element=A.top();
            A.pop();
            B.push(element);
        }
        T element = A.top();
        A.pop();
        B.push(element);
        while(!B.empty()){
            T element = B.top();
            B.pop();
            A.push(element);
        }
        return element;
    };
    int size(){
        return A.size()+B.size();
    };
    bool empty(){
        return size()==0;
    };


};
int main() {
    Queue<int> q;
    q.push(2);
    q.push(3);
    q.push(4);
    q.pop();
    q.push(15);
    while(!q.empty())
    {
        cout<<q.front()<<" ";
        q.pop();
    }
    return 0;
}

还有一件事,在此之前我使用两个队列实现了 Stack,并且 swap() 给出了正确的答案。

【问题讨论】:

    标签: c++ stl queue stack swap


    【解决方案1】:

    当您手动交换堆栈时,您可以通过从一个堆栈顶部取出一个元素并将其放在另一个堆栈顶部来实现。这将反转堆栈中元素的顺序。

    当您使用std::swap 交换两个堆栈时,将保留当前顺序。最终结果是堆栈中的顺序颠倒了。通过使用另一个手动“交换”,您可以重新反转所有元素并恢复原始顺序(但删除了底部元素,因为在交换期间您没有将其添加到 B 堆栈中)。

    【讨论】:

      猜你喜欢
      • 2010-10-15
      • 2012-09-02
      • 2021-02-05
      • 2014-04-21
      • 2010-09-09
      • 2021-07-08
      • 2014-12-23
      • 1970-01-01
      • 2018-06-14
      相关资源
      最近更新 更多