Leetcode# 225. Implement Stack using Queues

public class MyStack {

    /** Initialize your data structure here. */
    Queue pq = new LinkedList();
    public MyStack() {
        
    }
    
    /** Push element x onto stack. */
    public void push(int x) {
        pq.add(x);
        for(int i=1;i

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

232. Implement Queue using Stacks

public class MyQueue {

    /** Initialize your data structure here. */
    Stack in = new Stack();
    Stack 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();
 */

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

你可能感兴趣的:(Leetcode# 225. Implement Stack using Queues)