if (!stackOut.isEmpty()) return; while (!stackIn.isEmpty()){ stackOut.push(stackIn.pop()); } } private Stack<Integer> stackIn; private Stack<Integer> stackOut; }
/** * Your MyQueue object will be instantiated and called as such: * MyQueue obj = new MyQueue(); * obj.push(x); * int param_2 = obj.pop(); * int param_3 = obj.peek(); * boolean param_4 = obj.empty(); */
classMyStack { /** Java标准库中 : 栈 :Stack push:往栈顶添加元素(存) pop:从栈顶移除元素(获取的是最后一个存的东西) peek:获取栈顶元素,并不做任何添加删除操作 队列 : Quene offer:入队 poll:出队 peek:获取队头元素,并不做任何添加删除操作 用队列实现栈 MyStack.push 也就是存(存在第一位) MyStack.pop/peek 也就是获取最后一个存的东西 */ /** 队列是先进先出的规则,把一个队列中的数据导入另一个队列中,数据的顺序并没有变,并没有变成先进后出的顺序。 所以用栈实现队列, 和用队列实现栈的思路还是不一样的,这取决于这两个数据结构的性质。 但是依然还是要用两个队列来模拟栈,只不过没有输入和输出的关系,而是另一个队列完全用来备份的! 用两个队列que1和que2实现队列的功能,que2其实完全就是一个备份的作用,把que1最后面的元素以外的元素都备份到que2,然后弹出最后面的元素,再把其他元素从que2导回que1。 */ publicMyStack() { queue1 = newLinkedList<>(); queue2 = newLinkedList<>(); } /** Push element x onto stack. */ publicvoidpush(int x) { queue2.offer(x); // 先放在辅助队列中 while (!queue1.isEmpty()){ queue2.offer(queue1.poll()); } Queue<Integer> queueTemp; queueTemp = queue1; queue1 = queue2; queue2 = queueTemp; // 最后交换queue1和queue2,将元素都放到queue1中 } /** Removes the element on top of the stack and returns that element. */ publicintpop() { return queue1.poll(); // 因为queue1中的元素和栈中的保持一致,所以这个和下面两个的操作只看queue1即可 } /** Get the top element. */ publicinttop() { return queue1.peek(); } /** Returns whether the stack is empty. */ publicbooleanempty() { return queue1.isEmpty(); } private Queue<Integer> queue1; private Queue<Integer> queue2; }
/** * 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(); */