栈和队列的常见面试题-栈实现队列-队列实现栈
)
1) 用栈结构实现队列结构
解析:
用两个栈:push栈,pop栈
push栈:存储数据
pop 栈:只要本栈数据不为空,便将push栈数据倒出致此,实现队列
public static class TwoStacksQueue {
public Stack<Integer> stackPush;
public Stack<Integer> stackPop;
public TwoStacksQueue() {
stackPush = new Stack<Integer>();
stackPop = new Stack<Integer>();
}
// push栈向pop栈倒入数据
private void pushToPop() {
if (stackPop.empty()) {
while (!stackPush.empty()) {
stackPop.push(stackPush.pop());
}
}
}
/*add & push
共同点:
add,push都可以向stack中添加元素。
不同点:
add是继承自Vector的方法,且返回值类型是boolean。
push是Stack自身的方法,返回值类型是参数类类型。*/
public void add(int pushInt) {
stackPush.push(pushInt);
pushToPop();
}
//返回栈顶元素,并且将该元素出栈。
public int pop() {
if (stackPop.empty() && stackPush.empty()) {
throw new RuntimeException("Queue is empty!");
}
pushToPop();
return stackPop.pop();
}
//返回栈顶元素,但不弹出该元素。
public int peek() {
if (stackPop.empty() && stackPush.empty()) {
throw new RuntimeException("Queue is empty!");
}
pushToPop();
return stackPop.peek();
}
}
2) 如何用队列结构实现栈结构
解析:
用两个栈:push栈,pop栈
push,help两栈相互倒元素(只剩一个元素),实现栈功能
public static class TwoQueueStack<T> {
public Queue<T> queue;
public Queue<T> help;
public TwoQueueStack() {
queue = new LinkedList<>();
help = new LinkedList<>();
}
public void push(T value) {
queue.offer(value);// add()和offer()
}
//返回元素,并弹出该元素
public T poll() {
while (queue.size() > 1) {
help.offer(queue.poll());// poll()和remove()拿出来
}
T ans = queue.poll();
Queue<T> tmp = queue;
queue = help;
help = tmp;
return ans;
}
//返回元素,但不弹出
public T peek() {
while (queue.size() > 1) {
help.offer(queue.poll());
}
T ans = queue.poll();
help.offer(ans);
Queue<T> tmp = queue;
queue = help;
help = tmp;
return ans;
}
public boolean isEmpty() {
return queue.isEmpty();
}
}
3. 扩展
前言:
图的 宽度优先遍历一般使用队列实现 深度优先遍历一般使用栈实现
若用栈怎么实现图的宽度优先遍历?
若用队列怎么实现图的深度优先遍历?
答案显而易见的