题目来源:
leetcode题目,网址:面试题 03.04. 化栈为队 - 力扣(LeetCode)
解题思路:
初始时,有两个空栈 stack1 和 stack2,将 stack1 作为输入栈,stack2 作为输出栈。
入栈,直接入栈 stack1.
出栈,若 stack2 非空,直接从 stack 2 中出栈;否则,将 stack1 中元素出栈并压入 stack2 中,然后再将 stack2 栈顶元素出栈。
查看栈顶元素,若 stack2 非空,直接返回 stack 2 栈顶元素即可;否则,将 stack1 中元素出栈并压入 stack2 中,然后返回 stack2 栈顶元素。
判空,两站大小之和是否为 0.
解题代码:
- class MyQueue {
- private:
- stack<int> stack1;
- stack<int> stack2;
- public:
- /** Initialize your data structure here. */
- MyQueue() {
- while(!stack1.empty()){
- stack1.pop();
- }
- while(!stack2.empty()){
- stack2.pop();
- }
- }
-
- /** Push element x to the back of queue. */
- void push(int x) {
- stack1.push(x);
- }
-
- /** Removes the element from in front of queue and returns that element. */
- int pop() {
- if(stack2.empty()){
- while(!stack1.empty()){
- stack2.push(stack1.top());
- stack1.pop();
- }
- }
- int temp=stack2.top();
- stack2.pop();
- return temp;
- }
-
- /** Get the front element. */
- int peek() {
- if(stack2.empty()){
- while(!stack1.empty()){
- stack2.push(stack1.top());
- stack1.pop();
- }
- }
- return stack2.top();
- }
-
- /** Returns whether the queue is empty. */
- bool empty() {
- return stack1.size()+stack2.size()==0;
- }
- };
-
- /**
- * Your MyQueue object will be instantiated and called as such:
- * MyQueue* obj = new MyQueue();
- * obj->push(x);
- * int param_2 = obj->pop();
- * int param_3 = obj->peek();
- * bool param_4 = obj->empty();
- */
总结:
和官方题解思路一样。