剑指offer第七题,由先入后出的栈来实现先入先出的队列,将栈1用来存放入队元素,栈2用来出队
package com.zjy.sword2offer;
import java.util.Stack;
public class CQueue {
private Stack<Integer> sta1 = new Stack<Integer>();
private Stack<Integer> sta2 = new Stack<Integer>();
public void poll(int key){
sta1.push(key);
}
public int remove() throws Exception{
if(sta2.isEmpty())
{
if(sta1.isEmpty())
throw new Exception("Empty Queue!");
while(!sta1.isEmpty())
{
sta2.push(sta1.pop());
}
}
int res = sta2.pop();
return res;
}
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
CQueue cq = new CQueue();
cq.poll(1);
cq.remove();
//cq.remove();
cq.poll(1003);
System.out.println(cq.remove());
}
}