255.用队列实现堆栈

------------恢复内容开始------------

 思路:主要是把先进先出变成先进后出,最简单的思路就是每次进去一个元素,把队列里面存在的元素全部给放到这个元素的后面去,让这个元素在队伍首。

这题主要是让我学习了一下java的queue的类,之前一直没有用过java的类。

来个廖雪峰的java学习:https://www.liaoxuefeng.com/wiki/1252599548343744/1265121791832960

然后自己的代码:

import java.util.Queue;
class MyStack {
    private 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=queue.size()-1;i>0;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.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 {
    private 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 = queue.size() - 1; i > 0; 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.isEmpty();
    }
}

------------恢复内容结束------------

原文地址:https://www.cnblogs.com/William-xh/p/13673969.html