225. 用队列实现栈

2020-03-08  本文已影响0人  梦想黑客

题目描述

使用队列实现栈的下列操作:

解法一

class MyStack {
    //push的时候逆序队列,让最后放入的在最前面

    private Queue<Integer> data;

    /** Initialize your data structure here. */
    public MyStack() {
        data = new LinkedList<>();
    }
    
    /** Push element x onto stack. */
    public void push(int x) {
        data.offer(x);

        int size = data.size();
        while(size > 1){
            data.offer(data.poll());
            size--;
        }
   
    }
    
    /** Removes the element on top of the stack and returns that element. */
    public int pop() {
    
        return data.poll();
    }
    
    /** Get the top element. */
    public int top() {
        return data.peek();
    }
    
    /** Returns whether the stack is empty. */
    public boolean empty() {
        return data.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();

解法二

class MyStack {
    //通过2个队列转换,data1为主队列

    private Queue<Integer> data1;
    private Queue<Integer> data2; 

    /** Initialize your data structure here. */
    public MyStack() {
        data1 = new LinkedList<>();
        data2 = new LinkedList<>();
    }
    
    /** Push element x onto stack. */
    public void push(int x) {

        //如果data1不为空,则使为空的data2 等于 data1
        if(!data1.isEmpty()){
            Queue<Integer> tmp = data1;
            data1 = data2;
            data2 = tmp;
        }
     

        data1.offer(x);

        while(!data2.isEmpty()){
            data1.offer(data2.poll());
        }
   
    }
    
    /** Removes the element on top of the stack and returns that element. */
    public int pop() {
    
        return data1.poll();
    }
    
    /** Get the top element. */
    public int top() {
        return data1.peek();
    }
    
    /** Returns whether the stack is empty. */
    public boolean empty() {
        return data1.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();
 */
上一篇下一篇

猜你喜欢

热点阅读