Implement Stack using Two Queues

后端 未结 23 827
感情败类
感情败类 2020-11-28 17:05

A similar question was asked earlier there, but the question here is the reverse of it, using two queues as a stack. The question...

Given two queues with their sta

23条回答
  •  旧时难觅i
    2020-11-28 17:36

    #include 
    using namespace std;
    queueQ;
    stackStk;
    void PRINT(stackss , queueqq) {
        while( ss.size() ) {
            cout << ss.top() << " " ;
            ss.pop();
        }
        puts("");
        while( qq.size() ) {
            cout << qq.front() << " " ;
            qq.pop();
        }
        puts("\n----------------------------------");
    }
    void POP() {
        queueTmp ;
        while( Q.size() > 1 ) {
            Tmp.push( Q.front()  );
            Q.pop();
        }
        cout << Q.front() << " " << Stk.top() << endl;
        Q.pop() , Stk.pop() ;
        Q = Tmp ;
    }
    void PUSH(int x ) {
        Q.push(x);
        Stk.push(x);
    }
    int main() {
        while( true ) {
            string typ ;
            cin >> typ ;
            if( typ == "push" ) {
                int x ;
                cin >> x;
                PUSH(x);
            } else POP();
            PRINT(Stk,Q);
        }
    }
    

提交回复
热议问题