剑指offer刷题第五题
第五题 用两个栈实现队列,leetcode232
思路:加入元素时加入栈1,Pop时先看栈2是否为空,如果栈2为空,把栈1中所以元素依次Pop再Push进栈2即可得到队列的效果。比如加入1,2,3,这时栈1从上到下为3,2,1;栈2为空,把3Pop再Push进栈2,再对2、1进行操作,这样之后栈1为空,栈2从上到下为1,2,3。再Pop队列2即可得到1。
如果这时再加入4,只需判断栈2是否为空,只要栈2不空直接Pop得到2,与队列是相同效果。
代码:
import java.util.Stack; public class Solution { Stack<Integer> stack1 = new Stack<Integer>(); Stack<Integer> stack2 = new Stack<Integer>(); public void push(int node) { stack1.push(node); } public int pop() { if(stack2.isEmpty()) { while(!stack1.isEmpty()) { int x = stack1.pop(); stack2.push(x); } } return stack2.pop(); } }
还有一道用两个队列模拟栈的题leetcode225
思路:加入时加入队列1,Pop时有三种情况:
1.队列1有元素,队列2无元素:这时需要把队列1的元素依次拿出放至队列2直到队列1只剩1个元素,将该元素Pop即可。比如加入1,2,3,队列1中有1,2,3,队列2为空。把1,2加入队列2,这时队列2为1,2,队列1中剩下的3就是要Pop的元素。
2.队列1无元素,队列2有元素:这时把队列2的元素依次拿出放至队列1直到队列2只剩1个元素,将该元素Pop即可。比如刚才队列2是1,2,队列1为空,这时Pop的元素应该是2,那么根据操作把1加入队列1,队列2剩下2Pop即可。
3.队列1有元素,队列2有元素:这时把队列1的元素依次拿出放至队列2直到队列1只剩1个元素,将该元素Pop即可。比如加入1,2,3,然后Pop出3,再加入4,5,安装之前的操作这时队列1为4,5,队列2位1,2,这时应该Pop的元素是5,所以把4加入队列2,把5Pop即可。
peek与pop大体思路相同。
代码:
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) { queue1.offer(x); } /** Removes the element on top of the stack and returns that element. */ public int pop() { if(queue1.isEmpty()) { while(queue2.size() > 1) queue1.offer(queue2.poll()); return queue2.poll(); } else { while(queue1.size() > 1) queue2.offer(queue1.poll()); return queue1.poll(); } } /** Get the top element. */ public int top() { if(queue1.isEmpty()) { while(queue2.size() > 1) queue1.offer(queue2.poll()); int x = queue2.peek(); queue1.offer(queue2.poll()); return x; } else { while(queue1.size() > 1) queue2.offer(queue1.poll()); int x = queue1.peek(); queue2.offer(queue1.poll()); return x; } } /** Returns whether the stack is empty. */ public boolean empty() { return queue1.isEmpty() && queue2.isEmpty(); } }