(232)-(Implement Queue using Stacks )-(用两个栈实现队列)-(先分析清楚这个逻辑,写代码很快的)
//进元素时,【1】有,【2】空,直接从【1】进栈,而且可以连续进的
//进元素时,【1】空,【2】有,将【2】中所有元素,依次出栈,然后从【1】进栈
// 【1】有,【2】空,直接从【1】进栈,而且可以连续进的
//出元素时,【1】空,【2】有,直接从【2】出栈
//出元素时,【1】有,【2】空,将【1】中所有元素,依次出栈,然后从【2】进栈,
// 【1】空,【2】有,直接从【2】出栈
class MyQueue
{
Stack<Integer> fir_stack = new Stack<Integer>();
Stack<Integer> sec_stack = new Stack<Integer>();
//进元素时
// Push element x to the back of queue.
public void push(int x)
{
//【2】空
if(sec_stack.empty()==true)
{
fir_stack.push(x);
}
else
{
while(sec_stack.empty()==false)
{
Integer temp =sec_stack.peek();//获取首元素
fir_stack.push(temp); //进栈到【1】
sec_stack.pop(); //从【2】中出栈
}
fir_stack.push(x);
}
}
//出元素时
// Removes the element from in front of queue.
public void pop()
{
//【2】有,直接从【2】出
if(sec_stack.empty()!=true)
{
sec_stack.pop();
}
//【2】木有
else
{
while(fir_stack.empty()==false)
{
Integer temp =fir_stack.peek();//获取首元素
sec_stack.push(temp); //进栈到【2】
fir_stack.pop(); //从【1】中出栈
}
sec_stack.pop();
}
}
// Get the front element.
public int peek()
{
//【2】有,直接从【2】出
if(sec_stack.empty()!=true)
{
Integer temp=sec_stack.peek();
int temp_val=temp.intValue();
return temp_val;
}
//【2】木有
else
{
while(fir_stack.empty()==false)
{
Integer temp =fir_stack.peek();//获取首元素
sec_stack.push(temp); //进栈到【2】
fir_stack.pop(); //从【1】中出栈
}
Integer temp=sec_stack.peek();
int temp_val=temp.intValue();
return temp_val;
}
}
// Return whether the queue is empty.
public boolean empty()
{
if(fir_stack.empty()==true && sec_stack.empty()==true)
{
return true;
}
else
{
return false;
}
}
}