Last active
October 23, 2018 14:36
-
-
Save imgen/42dc3e7c50d2d780437e51e3bf74f1d9 to your computer and use it in GitHub Desktop.
Queue implemented in stacks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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