本文主要是介绍leetcode Implement Stack using Queues,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Implement Stack using Queues 题目:https://leetcode.com/problems/implement-stack-using-queues/
Implement Stack using Queues
解题思路:使用两个队列实现栈,始终保持一个队列为空。
class MyStack {Queue<Integer> queue1=new LinkedList<>();Queue<Integer> queue2=new LinkedList<>();/** Initialize your data structure here. */public MyStack() {}/** Push element x onto stack. */public void push(int x) {if(queue1.isEmpty()){queue1.offer(x);while(!queue2.isEmpty()){Integer peek = queue2.peek();queue2.poll();queue1.offer(peek);}}else{queue2.offer(x);while(!queue1.isEmpty()){Integer peek = queue1.peek();queue1.poll();queue2.offer(peek);}}}/** Removes the element on top of the stack and returns that element. */public int pop() {if(!queue1.isEmpty()){return queue1.poll();}if(!queue2.isEmpty()){return queue2.poll();}return 0;}/** Get the top element. */public int top() {if(!queue1.isEmpty()){return queue1.peek();}if(!queue2.isEmpty()){return queue2.peek();}return 0;}/** Returns whether the stack is empty. */public boolean empty() {return queue1.isEmpty() && queue2.isEmpty();}
}
这篇关于leetcode Implement Stack using Queues的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!