Java用两个栈实现队列
import java.util.Stack;
import org.junit.Test;
public class QueueByTwoStack {
private Stack<Integer> stack1=new Stack<Integer>();
private Stack<Integer> stack2=new Stack<Integer>();
public QueueByTwoStack() {
super();
}
/**
* 入队
* @param ele 要入队的元素
*/
private void push(int ele){
stack1.push(ele);
}
/**
* 出队
* @return 队首元素
*/
public int pop(){
if(stack1.isEmpty() && stack2.isEmpty()){
try {
throw new Exception("队列空");
} catch (Exception e) {
e.printStackTrace();
}
}
while(stack2.size()<=0){
while(stack1.size()>0){
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
/**
* 判断是否队空
* @return
*/
private boolean isEmpty(){
if(stack1.isEmpty() && stack2.isEmpty()){
return true;
}else{
return false;
}
}
/**
*查看队首元素
* @return 队首元素
*/
public int peek(){
if(isEmpty()){
try {
throw new Exception("队列空");
} catch (Exception e) {
e.printStackTrace();
}
}else{
while(stack2.isEmpty()){
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
}
}
return stack2.peek();
}
@Test
public void testQueueByTwoStack(){
QueueByTwoStack q=new QueueByTwoStack();
for (int i = 0; i <10; i++) {
q.push(i);
}
System.out.println("队列出队序列:");
while(!q.isEmpty()){
System.out.print(q.pop()+" ");
}
}
}