Queue and Stack Classes in C#
By Mash B
The Queue and Stack classes (in the System.Collections namespace) store objects that
can be retrieved and removed in a single step. Queue uses a FIFO sequence, while
Stack uses a LIFO sequence. The Queue class uses the Enqueue and Dequeue methods
to add and remove objects, while the Stack class uses Push and Pop.
The following code demonstrates the differences between the two classes:
//
Queue
Queue q = new Queue();
q.Enqueue("Hello");
q.Enqueue("world");
q.Enqueue("just testing");
Console.WriteLine("Queue demonstration:");
for (int i = 1; i <= 3; i++)
Console.WriteLine(q.Dequeue().ToString());
The application produces the following output:
Queue
demonstration:
Hello
world
just testing
// Stack
Stack s = new Stack();
s.Push("Hello");
s.Push("world");
s.Push("just testing");
Console.WriteLine("Stack demonstration:");
for (int i = 1; i <= 3; i++)
Console.WriteLine(s.Pop().ToString());
The application produces the following output:
Stack
demonstration:
just testing
world
Hello
You can
also use Queue.Peek and Stack.Peek to access an object without removing it
from
the stack. Use Queue.Clear and Stack.Clear to remove all objects from the stack.
Queue and Stack Classes in C# (1060 Views)