package java程序员面试笔试宝典;
import java.util.LinkedList;
import java.util.Queue;
public class 两个队列模拟栈<E> {
LinkedList<E> q1=new LinkedList<E>();
LinkedList<E> q2=new LinkedList<E>();
public boolean isEmpty(){
return q1.isEmpty()&&q2.isEmpty();
}
public int size(){
return q1.size();
}
public E push(E data){
q1.add(data);
return data;
}
public E pop(){
if(isEmpty()){
return null;
}else if(q1.size()==1){
return q1.pop();
}else{
while(q1.size()>1){
q2.push(q1.pop());
}
E data=q1.pop();
while(q2.size()>0){
q1.push(q2.pop());
}
return data;
}
}
public static void main(String[] args) {
两个队列模拟栈<Integer> st=new 两个队列模拟栈<Integer>();
System.out.println(st.isEmpty());
System.out.println(st.size());
System.out.println(st.push(1));
System.out.println(st.push(2));
System.out.println(st.push(3));
//System.out.println(st.q1.size());
//System.out.println(st.q2.size());
System.out.println(st.pop());
System.out.println(st.pop());
System.out.println(st.isEmpty());
System.out.println(st.size());
System.out.println(st.pop());
}
}
两个队列模拟栈
猜你喜欢
转载自blog.csdn.net/m0_38068868/article/details/81209489
今日推荐
周排行