北京网站建设有哪些,wordpress标签聚合美化,烟台网站建设方案报价,wordpress删除媒体库数据题目描述
感觉栈实现队列更简单#xff0c;不过这个也还好写法有点像 JVM GC 里的复制算法
思路 代码
两个队列实现栈#xff1a;from、tofrom#xff1a;实际上的栈#xff0c;存储元素就是按照栈的顺序来#xff0c;负责pop、topto#xff1a;辅助队列#…题目描述
感觉栈实现队列更简单不过这个也还好写法有点像 JVM GC 里的复制算法
思路 代码
两个队列实现栈from、tofrom实际上的栈存储元素就是按照栈的顺序来负责pop、topto辅助队列永远为空 是不是很像幸存区的 from to 呢 ^ ^MyStack.size() from.size()因为 to 为空队列只是函数过程可能暂存一下。push 要特别注意直接 push 到 to 里然后把 from 的元素逐个 push 到 to 中此时 to 为实际上的栈然后再 from to 互换引用。
/*** 思路使用辅助队列每次push都替一下保证实际上 queue1 是按照栈顺序来的* 还是有点类似 JVM GC 的复制算法
*/
class MyStack {LinkedListInteger from;LinkedListInteger to;/** Initialize your data structure here. */public MyStack() {from new LinkedList();to new LinkedList();}// add相当于 Queue.push()// removeFirst: 相当于 Queue.pop()/** Push element x onto stack. */public void push(int x) {to.add(x);while(!from.isEmpty()){to.add(from.removeFirst());}LinkedListInteger temp from;from to;to temp;}/** Removes the element on top of the stack and returns that element. */public int pop() {return from.removeFirst();}/** Get the top element. */public int top() {// 相当于 Queue.peek()return from.get(0);}/** Returns whether the stack is empty. */public boolean empty() {return from.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();*/更新版
换成 ArrayDeque
class MyStack {DequeInteger in;DequeInteger out;public MyStack() {in new ArrayDeque();out new ArrayDeque();}public void push(int x) {in.offer(x);while(!out.isEmpty()) {in.offer(out.poll());}DequeInteger temp in;in out;out temp;}public int pop() {return out.pop();}public int top() {return out.element();}public boolean empty() {return out.isEmpty();}
}