Problem: Implement a queue using stacks.
Solution 1: Use a helper stack
public class Queue<T>
{
private readonly Stack<T> _front;
private readonly Stack<T> _helper;
public Queue()
{
_helper = new Stack<T>();
_front = new Stack<T>();
}
public void Enqueue(T data)
{
_front.Push(data);
}
public T Dequeue()
{
while (_front.Any())
{
_helper.Push(_front.Pop());
}
T data = _helper.Pop();
while (_helper.Any())
{
_front.Push(_helper.Pop());
}
return data;
}
public T Peek()
{
while (_front.Any())
{
_helper.Push(_front.Pop());
}
T data = _helper.Pop();
_front.Push(data);
while (_helper.Any())
{
_front.Push(_helper.Pop());
}
return data;
}
}