《剑指offer》面试题9(相关题目):两个队列实现一个栈。
思路:入栈:如果队列1和队列2都为空,则将元素放入队列1中表示入栈;如果2个队列有一个不为空,则将待入栈的元素放到这个不为空的队列中表示入栈。出栈:如果队列1和队列2都为空,出栈异常(栈为空);如果队列1不为空,则将队列1的元素依次出队列至队列2中,直至队列1只剩余一个元素(为待出栈元素),将该元素出队列(出栈);如果队列2不为空,则将队列2的元素依次出队列至队列1中,直至队列2只剩余一个元素(为待出栈元素),将该元素出队列(出栈)。
代码如下:
import java.util.Queue;
import java.util.LinkedList;
public class MyStack {
Queue<Integer> queue1 = new LinkedList<>();
Queue<Integer> queue2 = new LinkedList<>();
public void push (int node) {
if (queue1.isEmpty() && queue2.isEmpty()) {
queue1.add(node);
}
if (!queue1.isEmpty()) {
queue1.add(node);
}
if (!queue2.isEmpty()) {
queue2.add(node);
}
}
public int pop() {
if (queue1.isEmpty() && queue2.isEmpty()) {
throw new RuntimeException("stack is empty");
}
if (queue1.isEmpty()) {
while (queue2.size() > 1) {
queue1.add(queue2.poll());
}
return queue2.poll();
}
if (queue2.isEmpty()) {
while (queue1.size() > 1) {
queue2.add(queue1.poll());
}
return queue1.poll();
}
return (Integer)null;
}
}
网友评论