Leetcode# 225. Implement Stack using Queues

public class MyStack {

    /** Initialize your data structure here. */
    Queue<Integer> pq = new LinkedList<Integer>();
    public MyStack() {
        
    }
    
    /** Push element x onto stack. */
    public void push(int x) {
        pq.add(x);
        for(int i=1;i<pq.size();i++)
            pq.add(pq.poll());
    }
    
    /** Removes the element on top of the stack and returns that element. */
    public int pop() {
        return pq.poll();
    }
    
    /** Get the top element. */
    public int top() {
        return pq.peek();
    }
    
    /** Returns whether the stack is empty. */
    public boolean empty() {
        return pq.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();
 */

用队列实现堆栈,关键在于push的时候,将队列中的所有数反转一遍。

232. Implement Queue using Stacks

public class MyQueue {

    /** Initialize your data structure here. */
    Stack<Integer> in = new Stack();
    Stack<Integer> out = new Stack();
    public MyQueue() {
        
    }
    
    /** Push element x to the back of queue. */
    public void push(int x) {
        in.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        peek();
        return out.pop();
    }
    /** Get the front element. */
    public int peek() {
        if(out.isEmpty()){
            while(!in.isEmpty())
                out.push(in.pop());
        }
        return out.peek();
    }
    
    /** Returns whether the queue is empty. */
    public boolean empty() {
        return in.isEmpty()&&out.isEmpty();
    }
}

/**
 * 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();
 * boolean param_4 = obj.empty();
 */

用堆栈实现队列,技术点在维护两个堆栈。

    原文作者:尴尴尬尬先生
    原文地址: https://www.jianshu.com/p/57f23712a109
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞