首先理一下思路
s1:用于入栈。
s2:用于出栈。
(1)入队列:直接将元素压入s1;
(2)出队列:如果s2不为空,把s2中的栈顶元素直接弹出;否则,把s1的所有元素全部倒到s2中,再弹出s2的栈顶元素。
class MyQueue<T>
{
//定义两个堆栈
private Stack<T> stack1;
private Stack<T> stack2;
public MyQueue()
{
stack1=new Stack<T>();
stack2=new Stack<T>();
}
public void appentTail(T ele)
{ //尾部插入
stack1.push(ele);
}
public T deleteHead() throws Exception
{ //头部删除
if(stack2.isEmpty())
{ //如果stack2为空
while(!stack1.isEmpty())
{ //stack1的元素全部倒入stack2
stack2.push(stack1.pop());
}
}
if(stack2.isEmpty()) throw new Exception("队列为空");
return stack2.pop();
}
}