package cn.itcast;
import org.junit.Test;
import java.util.Stack;
public class StackQueue {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node){
stack1.push(node);
}
public int pop(){
if(stack2.empty()){
while(!stack1.empty())
stack2.push(stack1.pop());
}
return stack2.pop();
}
public static void main(String[] args) {
StackQueue stack = new StackQueue();
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
}
}
这个是一个先进先出的队列,push是压栈即装子弹,pop是弹栈即从弹夹中取子弹,只能从弹夹口取,利用这个方法实现这个功能。
第一步:装子弹。
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
全部先装在stack1中,顺序为 —>]]弹夹口1,2,3,4]|||封闭的弹夹尾 ;
第二步:取出子弹。
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
如果直接取出来肯定是4,3,2,1.
所以判断一下stack2d为空,stack1不为空的时候,把stack1中的东西装在stack2中。
然后就会出现弹出1,2,3,4的顺序。