当前位置:网站首页>Leetcode 232, queue with stack

Leetcode 232, queue with stack

2022-04-23 20:26:00 Die in a trap

232、 Using stack to realize queue

1) Title Description

Please use only two stacks to implement the FIFO queue . The queue should support all operations supported by the general queue (pushpoppeekempty):

Realization MyQueue class :

  • void push(int x) Put the element x Push to the end of the queue
  • int pop() Remove from the beginning of the queue and return the element
  • int peek() Returns the element at the beginning of the queue
  • boolean empty() If the queue is empty , return true ; otherwise , return false

explain :

  • you Can only Use standard stack operations —— It's just push to top, peek/pop from top, size, and is empty Operation is legal .
  • The language you use may not support stacks . You can use list perhaps deque( deque ) To simulate a stack , As long as it's a standard stack operation .

Example 1:

 Input :
["MyQueue", "push", "push", "peek", "pop", "empty"]
[[], [1], [2], [], [], []]
 Output :
[null, null, null, 1, 1, false]

 explain :
MyQueue myQueue = new MyQueue();
myQueue.push(1); // queue is: [1]
myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
myQueue.peek(); // return 1
myQueue.pop(); // return 1, queue is [2]
myQueue.empty(); // return false

Tips :

  • 1 <= x <= 9
  • Call at most 100 Time pushpoppeek and empty
  • Suppose all operations are valid ( for example , An empty queue will not call pop perhaps peek operation )

2) analysis

Because the stack is first in and last out , The queue is first in, first out , Two stacks can be used to exchange the order .

3)C++ Code

class MyQueue {
    
public:
    stack<int> s1;
    stack<int> s2;
    MyQueue() {
    
        
    }
    
    void push(int x) {
    
        s1.push(x);
    }
    
    int pop() {
    
        if(s2.empty()){
    
            while(!s1.empty()){
    
                s2.push(s1.top());
                s1.pop();
            }
        }
        int res=s2.top();
        s2.pop();
        return res;
    }
    
    int peek() {
    
        if(s2.empty()){
    
            while(!s1.empty()){
    
                s2.push(s1.top());
                s1.pop();
            }
        }
        int res=s2.top();
        return res;
    }
    
    bool empty() {
    
        return s1.empty()&&s2.empty();
    }
};

/** * 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(); */

版权声明
本文为[Die in a trap]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204232023107405.html