Created
August 2, 2012 03:13
-
-
Save kflu/3232901 to your computer and use it in GitHub Desktop.
Using stacks to implement a Queue.
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; | |
using System.Collections.Generic; | |
using System.Diagnostics; | |
namespace ConsoleApplication7 | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var q = new MyQ<int>(); | |
q.Enqueue(1); | |
q.Enqueue(2); | |
q.Enqueue(3); | |
Debug.Assert(q.Count == 3); | |
Debug.Assert(q.Dequeue() == 1); | |
Debug.Assert(q.Dequeue() == 2); | |
Debug.Assert(q.Dequeue() == 3); | |
bool success = false; | |
try | |
{ | |
q.Dequeue(); | |
success = true; | |
} | |
catch (QueueEmpty) | |
{ | |
} | |
finally | |
{ | |
Debug.Assert(success == false); | |
} | |
} | |
} | |
class QueueEmpty : Exception { } | |
class MyQ<T> | |
{ | |
public Stack<T>[] s; | |
public int Count | |
{ | |
get { return s[0].Count + s[1].Count; } | |
} | |
public MyQ() | |
{ | |
s = new Stack<T>[2]{ | |
new Stack<T>(), | |
new Stack<T>()}; | |
} | |
public void Enqueue(T obj) | |
{ | |
s[0].Push(obj); | |
} | |
public T Dequeue() | |
{ | |
if (s[1].Count==0) | |
{ | |
this.MoveItems(); | |
} | |
if (s[1].Count==0) | |
{ | |
throw new QueueEmpty(); | |
} | |
else | |
{ | |
return s[1].Pop(); | |
} | |
} | |
private void MoveItems() | |
{ | |
while (s[0].Count != 0) | |
{ | |
s[1].Push(s[0].Pop()); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment