《LeetCode力扣练习》代码随想录——栈与队列(用队列实现栈---Java)

《LeetCode力扣练习》代码随想录——栈与队列(用队列实现栈—Java)



刷题思路来源于 代码随想录

225. 用队列实现栈
  • 没有算法
    class MyStack {
    
        private ArrayDeque<Integer> queue;
    
        public MyStack() {
    
            queue=new ArrayDeque<>();
    
        }
        
        public void push(int x) {
    
            queue.offer(x);
    
        }
        
        public int pop() {
    
            int n=queue.size()-1;
    
            while(n>0){
                queue.offer(queue.poll());
                n--;
            }
    
            return queue.poll();
    
        }
        
        public int top() {
    
            return queue.getLast();
    
        }
        
        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();
     */
    

你可能感兴趣的:(LeetCode,leetcode,java,算法)