题目:用两个栈实现一个队列.实现两个函数:appendTail和deleteHead
思路:画图分析一下即可
import java.util.Stack;
public class Stack2Queue
{
private Stack
s1;
private Stack
s2;
private int size;
public Stack2Queue() {
s1 = new Stack
();
s2 = new Stack
(); size= 0; } public void appendTail(T source){ s1.push(source); size++; } public T deleteHead(){ if(s2.isEmpty()){ while(!s1.isEmpty()){ s2.push(s1.pop()); } } size--; return s2.pop(); } public boolean isEmpty(){ return size==0; } public static void main(String[] args) { Stack2Queue
q = new Stack2Queue<>(); for(int i=0;i<10;i++) q.appendTail(i); while(!q.isEmpty()){ System.out.println(q.deleteHead()); } } }