Skip to content

Instantly share code, notes, and snippets.

@imgen
Last active October 23, 2018 14:36
Show Gist options
  • Save imgen/42dc3e7c50d2d780437e51e3bf74f1d9 to your computer and use it in GitHub Desktop.
Save imgen/42dc3e7c50d2d780437e51e3bf74f1d9 to your computer and use it in GitHub Desktop.
Queue implemented in stacks
using System.Collections.Generic;
class QueueByStacks<T>
{
private Stack<T> _inStack, _outStack;
public QueueByStacks()
{
_inStack = new Stack<T>();
_outStack = new Stack<T>();
}
public void Enqueue(T item)
{
_inStack.Push(item);
}
public T Dequeue()
{
if (_outStack.Count > 0)
{
return _outStack.Pop();
}
while (_inStack.Count > 0)
{
_outStack.Push(_inStack.Pop());
}
return _outStack.Count > 0? _outStack.Pop() : throw new InvalidOperationException("Nothing to dequeue");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment