题目:用栈实现队列

解法一:

定义两个栈,一个正序记录输入的数字,另一个则倒序记录

对于 push,每次压入元素时,需要重新记录 sk2;

对于 pop,每次弹出元素时,需要重新记录 sk1

MyQueue

 1class MyQueue
 2{
 3public:
 4    std::stack<int> sk1;
 5    std::stack<int> sk2;
 6    MyQueue()
 7    {
 8    }
 9
10    void push(int x)
11    {
12        sk1.push(x);
13        std::stack<int> temp_sk1 = sk1;
14        std::stack<int> temp_sk2;
15        for(int i = 0; i < sk1.size(); i++)
16        {
17            temp_sk2.push(temp_sk1.top());
18            temp_sk1.pop();
19        }
20        sk2 = std::move(temp_sk2);
21    }
22
23    int pop()
24    {
25        int res = sk2.top();
26        sk2.pop();
27        std::stack<int> temp_sk1, temp_sk2 = sk2;
28        for(int i = 0; i < sk2.size(); i++)
29        {
30            temp_sk1.push(temp_sk2.top());
31            temp_sk2.pop();
32        }
33        sk1 = std::move(temp_sk1);
34        return res;
35    }
36
37    int peek()
38    {
39        return sk2.top();
40    }
41
42    bool empty()
43    {
44        return sk1.empty();
45    }
46};

来源:语雀原笔记