1. 栈实现队列
思路:构建两个栈:Push栈和Pop栈;将Push栈中的数据倒入Pop栈中然后返回给用户,就实现了队列。需要注意两个条件:①Pop栈为空时才能其中倒入数据。②向Pop栈倒入数据时必须要倒完。
固定栈1入队,栈2出队。pop() 操作时,①如果两栈都为空,报异常;②如果出队栈有元素就出队;③如果出队栈为空,就把入队栈的元素都弹过来再出队。
import java.util.Stack;
public class e04StackToQueue {
private Stack<Integer> s1;
private Stack<Integer> s2;
public e04StackToQueue(){
s1=new Stack<>();
s2=new Stack<>();
}
public void add(int obj){
s1.push(obj);
}
public Integer poll(){
if (s1.isEmpty()&&s2.isEmpty()){
throw new RuntimeException("empty");
}
if (s2.isEmpty()){
while (!s1.isEmpty()){
s2.push(s1.pop());
}
}
return s2.pop();
}
public Integer peek(){
if (s1.isEmpty()&&s2.isEmpty()){
throw new RuntimeException("empty");
}
if (s2.isEmpty()){
while (!s1.isEmpty()){
s2.push(s1.pop());
}
}
return s2.peek();
}
}
2. 队列实现栈
图的深度优先遍历需要用栈来实现。
用队列实现图的深度优先遍历方法是:先用队列实现栈结构,再用栈结构实现图的深度优先遍历。
代码思路:构建两个队列:Data队列和help队列;压入数据时数据都进Data队列,假设队列中按顺序进入了1,2,3,4,5,返回数据时,把1,2,3,4 放入help队列,然后拿出Data中的5返回;接着改引用,将Data队列和help队列的引用交换;下次返回数据时就依然是把Data队列中的123放入help队列,然后拿出Data队列中的4返回,再交换两队列的引用,如此反复。
import java.util.LinkedList;
import java.util.Queue;
public class e05QueueToStack {
private Queue<Integer> queue;
private Queue<Integer> help;
public e05QueueToStack(){
queue=new LinkedList<>();
help=new LinkedList<>();
}
public void push(Integer e){
queue.add(e);
}
public int pop(){
if (queue.isEmpty()){
throw new RuntimeException("empty");
}
while (queue.size()!=1){
help.add(queue.poll());
}
int res=queue.poll();
swap();
return res;
}
public int peek(){
if (queue.isEmpty()){
throw new RuntimeException("empty");
}
while (queue.size()!=1){
help.add(queue.poll());
}
int res=queue.poll();
help.add(res);
swap();
return res;
}
public void swap(){
Queue<Integer> tmp=queue;
queue=help;
help=tmp;
}
}