19_232. 用栈实现队列
作者:互联网
题目描述:
解题思路:
- 想着利用两个栈stack1和stack2,把stack1当作队列,其pop和队列的pop一样,然后每次push数据,就把stack1中的数据,依次出栈并入栈stack2,这样stack2中的顺序,就是最开始的入栈顺序,然后将新数据入栈stack2,再把stack2中所有数据依次出栈并入栈stack1。结果超出时间限制。
- 题解中并不需要每次都倒腾两遍,而是利用两个栈,一个栈
inStack
当做入队时存放数据,一个outStack
当做出队存放数据的栈,因此每次入队,只需要inStack.push()
即可,出队时,如果outStack
为空,则将inStack
数据全部出栈,放入outStack
,再出栈即可。这种方法就避免了每次都要出栈入栈两次,减少了所消耗的时间。
代码
class MyQueue {
Deque<Integer> inStack= null;
Deque<Integer> outStack = null;
public MyQueue() {
inStack = new LinkedList<Integer>();
outStack = new LinkedList<Integer>();
}
public void push(int x) {
inStack.push(x);
}
public int pop() {
if (outStack.isEmpty()) {
while (!inStack.isEmpty()) {
outStack.push(inStack.pop());
}
}
return outStack.pop();
}
public int peek() {
if (outStack.isEmpty()) {
while (!inStack.isEmpty()) {
outStack.push(inStack.pop());
}
}
return outStack.peek();
}
public boolean empty() {
return (inStack.isEmpty() && outStack.isEmpty());
}
}
/**
* 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();
*/
标签:obj,19,outStack,pop,用栈,isEmpty,push,inStack,232 来源: https://www.cnblogs.com/forrestyu/p/16058370.html