[jobdu]用两个栈实现队列

思路比较简单。就是当要pop的时候,如果s2为空,才把s1的转过来。总之就是区分一下此时s2为空和非空的情况。 http://ac.jobdu.com/problem.php?pid=1512

#include <cstring>

#include <cstdio>

#include <stack>

using namespace std;

   

class Queue {

public:

    void push(int val) {

        s1.push(val);

    }

    int pop() {

        if (s2.empty())

        {

            while(!s1.empty())

            {

                int tmp = s1.top();

                s1.pop();

                s2.push(tmp);

            }

        }

        if (!s2.empty()) {      

            int tmp = s2.top();

            s2.pop();

            return tmp;

        }

        else {

            return -1;

        }

    }

private:

    stack<int> s1, s2;

};

   

int main() {

    Queue Q;

    int n; scanf("%d", &n);

    char flag[20]; int val;

    for (int i=0; i<n; ++i) {

        scanf("%s", flag);

        if (strcmp("PUSH", flag) == 0) {

            scanf("%d", &val);

            Q.push(val);

        } else if (strcmp("POP", flag) == 0) {

            printf("%d\n", Q.pop());

        }

    }

    return 0;

}

  

你可能感兴趣的:(job)