package lianxi;
import static org.junit.Assert.*;
import java.util.Arrays;
import java.util.Stack;
import org.junit.Test;
/*
* 题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
*/
/*
* 思路:队列是先进先出;栈是先进后出
*/
public class zhanheduilie {
Stack<Integer> stack1=new Stack();
Stack<Integer> stack2 =new Stack();
@Test
public void testName() throws Exception {
// stack2.push(20);
//
// System.out.println(stack2);
zhanheduilie z=new zhanheduilie();
z.push(10);
z.push(20);
z.push(30);
System.out.println(z.pop());
System.out.println(z.pop());
System.out.println(z.pop());
}
public void push(int node) {
stack1.push(new Integer(node));
}
public int pop() {
Integer r=null;
if(!stack2.isEmpty()){
r=stack2.pop();//如果stack2不是空的,则弹出第一个
//写上面一句的重要性:当多次弹出的时候,就要执行这一句
}else{
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
if(!stack2.isEmpty()){
r=stack2.pop();
}
}
return r;
}
}
import static org.junit.Assert.*;
import java.util.Arrays;
import java.util.Stack;
import org.junit.Test;
/*
* 题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
*/
/*
* 思路:队列是先进先出;栈是先进后出
*/
public class zhanheduilie {
Stack<Integer> stack1=new Stack();
Stack<Integer> stack2 =new Stack();
@Test
public void testName() throws Exception {
// stack2.push(20);
//
// System.out.println(stack2);
zhanheduilie z=new zhanheduilie();
z.push(10);
z.push(20);
z.push(30);
System.out.println(z.pop());
System.out.println(z.pop());
System.out.println(z.pop());
}
public void push(int node) {
stack1.push(new Integer(node));
}
public int pop() {
Integer r=null;
if(!stack2.isEmpty()){
r=stack2.pop();//如果stack2不是空的,则弹出第一个
//写上面一句的重要性:当多次弹出的时候,就要执行这一句
}else{
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
if(!stack2.isEmpty()){
r=stack2.pop();
}
}
return r;
}
}