225. Implement Stack using Queues


class MyStack {
    Queue<Integer> queue;

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

// 这个题的 解题要点是 把 queue 当作 stack 来用, 就是 每次push new element to 
// stack 的 时候, 重新排顺序, 按照 stack 的 顺序重排
// 这个题用一个 queue 就行

Implement the following operations of a stack using queues.

  • push(x) -- Push element x onto stack.
  • pop() -- Removes the element on top of the stack.
  • top() -- Get the top element.
  • empty() -- Return whether the stack is empty.

Example:

MyStack stack = new MyStack();

stack.push(1);
stack.push(2);  
stack.top();   // returns 2
stack.pop();   // returns 2
stack.empty(); // returns false

 


 

posted on 2018-11-06 10:01  猪猪&#128055;  阅读(114)  评论(0)    收藏  举报

导航