import java.util.*;
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
QueueAndStack st = new QueueAndStack();
for(int i=1;i<6;i++){
st.push(i);
}
while(!st.isEmpty()){
System.out.print(st.pop()+" ");
}
st.push(1);
st.push(2);
st.push(3);
System.out.println();
System.out.println(st.peek());
System.out.println(st.pop());
st.push(3);
System.out.println(st.pop());
System.out.println(st.pop());
}
}
class QueueAndStack{
//使用两个队列颠倒的方式去实现栈
//栈最大的区别不就是先进后出吗
//模拟出栈
//把一个队列的东西全部倒进另一个队列 只留下一个
private Queue<Integer> queue;
private Queue<Integer> help;
public QueueAndStack(){
queue = new LinkedList<Integer>();
help = new LinkedList<Integer>();
}
public void push(int data){
queue.offer(data);
}
public int pop(){
if(queue.isEmpty()){
throw new RuntimeException("Queue is empty!");
}
while(queue.size()!=1){
help.offer(queue.poll());
}
int res =queue.poll();
swap();
return res;
}
public int peek(){
if(queue.isEmpty()){
throw new RuntimeException("Queue is empty!");
}
while(queue.size()!=1){
help.offer(queue.poll());
}
int res =queue.poll();
help.offer(res);
swap();
return res;
}
public void swap(){//交换引用
Queue<Integer> temp =queue;
queue = help;
help = temp;
}
public boolean isEmpty(){
return queue.isEmpty();
}
}
用队列模拟栈
最新推荐文章于 2023-09-09 08:13:13 发布