题目:
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
解答:
①队列”先进先出”,栈”先进后出”。
开始的想法是以stack1为基准,保持整个顺序。如果出队列,就整个捣蹬到stack2里面,然后再都放回来。
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() {
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
int ans=stack2.pop();
while(!stack2.isEmpty()){
stack1.push(stack2.pop());
}
return ans;
}
}
运行时间: 9 ms
占用内存: 9420K
②利用上stack2
后来发现不用那么麻烦,一个栈压入元素,而另一个栈作为缓冲,将stack1的元素出栈后压入stack2中。也可以将stack1中的最后一个元素直接出栈,而不用压入stack2中再出栈。
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.empty()){
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
}
运行时间: 19 ms
占用内存: 9328K