【牛客】用两个栈来实现一个队列

题目链接:https://www.nowcoder.com/practice/54275ddae22f475981afa2244dd448c6?tpId=13&tqId=11158&tPage=1&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking

题目描述

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
 1 class Solution
 2 {
 3 public:
 4     void push(int node) {
 5         stack1.push(node);
 6         if(stack2.empty()){
 7             while(!stack1.empty()){
 8                 node=stack1.top();
 9                 stack2.push(node);
10                 stack1.pop();
11             }
12         }
13     }
14 
15     int pop() {
16         int node;
17         if(!stack2.empty()){
18             node=stack2.top();
19             stack2.pop();
20         }else{
21             while(!stack1.empty()){
22                 node=stack1.top();
23                 stack2.push(node);
24                 stack1.pop();
25             }
26             node=stack2.top();
27             stack2.pop();
28         }
29         return node;
30     }
31 
32 private:
33     stack<int> stack1;
34     stack<int> stack2;
35 };

 

posted @ 2020-04-12 16:21  wydxry  阅读(349)  评论(0编辑  收藏  举报
Live2D