两个栈实现一个队列
public class TwoStackImpAQuene {
public Stack<Integer> s1;//进队的栈
public Stack<Integer> s2;//出队的栈
public void push(int num){
s1.push(num);
}
public int size(){
return s1.size()+s2.size();
}
public int pop() throws Exception{
if (s2.isEmpty()){
while (!s1.isEmpty()){
s2.push(s1.pop());
}
}
if (s2.isEmpty()){
throw new Exception("队列为空");
}
return s2.pop();
****}
}
两个队列是实现一个栈
public class TwoQueneImpStack {
LinkedList<Integer> queue1 = new LinkedList();
LinkedList<Integer> queue2 = new LinkedList();
public void push(int value){
queue1.addLast(value);
}
public int size(){
return queue1.size()+queue2.size();
}
public int pop() throws Exception{
if (size()!=0){
if (!queue1.isEmpty()){
putOneToAnother();//q1的值只留一个其余放到空的q2中
return queue1.removeFirst();
}
if (!queue2.isEmpty()){
putOneToAnother();//q2的值只留一个其余放到空的q1中
return queue2.removeFirst();
}
}
throw new Exception("空了");
}
public void putOneToAnother(){
if (!queue1.isEmpty()){
while (queue1.size()>1){
queue2.addLast(queue1.removeFirst());
}
}else if (!queue2.isEmpty()){
while (queue2.size()>1){
queue1.addLast(queue2.removeFirst());
}
}
}
}