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