DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
Queue using 2 Stacks - C#
public class QueueUsing2Stacks
{
private Stack _stack1 = new Stack();
private Stack _stack2 = new Stack();
public QueueUsing2Stacks() { }
public void Enqueue(int data)
{
//Pop ALL existing elements from stack1, push them onto stack2
int _stack1Count = _stack1.Count;
for (int i = 0; i < _stack1Count; i++)
{
_stack2.Push(_stack1.Pop());
}
//Push new data onto stack1
_stack1.Push(data);
int _stack2Count = _stack2.Count;
//Pop ALL elements from stack2 and Push them back onto stack1
for (int i = 0; i < _stack2Count; i++)
{
_stack1.Push(_stack2.Pop());
}
}
public int Dequeue()
{
if (_stack1.Count == 0)
throw new Exception("Queue is Empty");
return _stack1.Pop();
}
}
Queue using 2 Stacks - C#





