232.用栈实现队class MyQueue { Stack<Integer> stackIn; Stack<Integer> stackOut; /** Initialize your data structure here. */ public MyQueue() { stackIn = new Stack<>(); // 负责进栈 stackOut = new Stack<>(); // 负责出栈 } /** Push element x to the back of queue. */ public void push(int x) { stackIn.push(x); } /** Removes the element from in front of queue and returns that element. */ public int pop() { dumpstackIn(); return stackOut.pop(); } /** Get the front element. */ public int peek() { dumpstackIn(); return stackOut.peek(); } /** Returns whether the queue is empty. */ public boolean empty() { return stackIn.isEmpty() && stackOut.isEmpty(); } // 如果stackOut为空,那么将stackIn中的元素全部放到stackOut中 private void dumpstackIn(){ if (!stackOut.isEmpty()) return; while (!stackIn.isEmpty()){ stackOut.push(stackIn.pop()); } } }
用两个栈来实现队列操作(类似于负负得正)
225. 用队列实现栈
// 使用两个 Queue 实现 class MyStack { Queue<Integer> queue1; // 和栈中保持一样元素的队列 Queue<Integer> queue2; // 辅助队列 /** Initialize your data structure here. */ public MyStack() { queue1 = new LinkedList<>(); queue2 = new LinkedList<>(); } /** Push element x onto stack. */ public void push(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. */ public int pop() { return queue1.poll(); // 因为queue1中的元素和栈中的保持一致,所以这个和下面两个的操作只看queue1即可 } /** Get the top element. */ public int top() { return queue1.peek(); } /** Returns whether the stack is empty. */ public boolean empty() { return queue1.isEmpty(); } }
用两个队列来实现栈的操作,一个是放和真正队列一样数据的栈,另一个是辅助队列来给主队列腾位置
class MyStack { // Deque 接口继承了 Queue 接口 // 所以 Queue 中的 add、poll、peek等效于 Deque 中的 addLast、pollFirst、peekFirst Deque<Integer> que1; /** Initialize your data structure here. */ public MyStack() { que1 = new ArrayDeque<>(); } /** Push element x onto stack. */ public void push(int x) { que1.addLast(x); } /** Removes the element on top of the stack and returns that element. */ public int pop() { int size = que1.size(); size--; // 将 que1 导入 que2 ,但留下最后一个值 while (size-- > 0) { que1.addLast(que1.peekFirst()); que1.pollFirst(); } int res = que1.pollFirst(); return res; } /** Get the top element. */ public int top() { return que1.peekLast(); } /** Returns whether the stack is empty. */ public boolean empty() { return que1.isEmpty(); } }
用一个队列其实就可以,把它放在后面,然后一次放到后面,一遍过后,出来的就是队列的顺序