queue via stacks: implement a my Queue class which implements a queue using 2 stacks.
通过2个stack实现 MyQueue类
public class MyQueue<T>
{
Stack<T> stackNew, stackOld;
public MyQueue()
{
stackNew = new Stack<T>();
stackOld = new Stack<T>();
}
public int Size()
{
return stackNew.Count+stackOld.Count;
}
/// <summary>
/// stackNew中加入新元素
/// </summary>
/// <param name="t"></param>
public void Add(T t)
{
stackNew.Push(t);
}
/// <summary>
/// 如果stackOld为空,把stackNew中的元素逐个move到stackOld中去;
/// 然后,peek和remove就好用了;
/// </summary>
public void ShiftStacks()
{
//一定要stackOld为空才操作,
if (stackOld.Count==0)
{
while (stackNew.Count != 0)
{
stackOld.Push(stackNew.Pop());
}
}
}
public T Peek()
{
ShiftStacks();
return stackOld.Peek();
}
public T Remove()
{
ShiftStacks();
return stackOld.Pop();
}
}
思路2:
1 定义两个stack:stack1, stack2
2 对于Add方法;如果stack2为空,直接push;如果不为空,从stack2倒回stack1,然后再push;
3 Peek方法, 如果stack1不为空,就从stack1 倒到stack2,然后stack2 pop;
举例:
1,2,3进入stack1, 如果需要pop;就执行步骤3
如果需要再Add,就执行Add