当前位置:网站首页>Daily question 1: force deduction: 225: realize stack with queue

Daily question 1: force deduction: 225: realize stack with queue

2022-07-06 22:21:00 Flying cats don't eat fish

subject

 Insert picture description here
** analysis : Use two queues to realize the structure of stack , We need to q1 and q2,q1 Keep consistent with the stack at all times ,q2 Used to play an auxiliary role . The only difference between the two is the difference of adding elements , The order of queue and stack should be opposite , therefore ,q2 The role of , Whenever an element is added to the stack ,q2 Add the element , And then q1 The elements in are queued out in turn , Enter again q2. Let's talk about it again q2 and q1 In exchange for , In order to make sure q1 Keep consistent with the elements in the stack at all times .**

class MyStack {
    

    public MyStack() {
    

    }
    
    Queue <Integer> q1 = new LinkedList<>();
    Queue <Integer> q2 = new LinkedList<>();

    public void push(int x) {
    
        q2.offer(x);
        while(!q1.isEmpty()){
    
            q2.offer(q1.poll());
        }
        Queue <Integer> temp;
        temp = q2;
        q2 = q1;
        q1 = temp; 
    }
    
    public int pop() {
    
        return q1.poll();
    }
    
    public int top() {
    
        return q1.peek();
    }
    
    public boolean empty() {
    
        return q1.isEmpty();
    }
}

/** * Your MyStack object will be instantiated and called as such: * MyStack obj = new MyStack(); * obj.push(x); * int param_2 = obj.pop(); * int param_3 = obj.top(); * boolean param_4 = obj.empty(); */
原网站

版权声明
本文为[Flying cats don't eat fish]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207061423228227.html