Leetcode 225. Implement Stack using Queues

Question: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

Answer

import java.util.LinkedList;
import java.util.Queue;

class MyStack {

    private Queue<Integer> q = new LinkedList<>();
    private Queue<Integer> temp = new LinkedList<>();
    // add element x at queue top 
    void push(int x){
        while(!q.isEmpty()){
            temp.add(q.poll());
        }
        q.add(x);
        while(!temp.isEmpty()){
            q.add(temp.poll());
        }
    }

    // remove
    void pop(){
        q.poll();
    }

    // retrieve but not remove
    Integer top(){
        return q.peek();
    }

    boolean empty(){
        return q.isEmpty();
    }
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。