C# Queue and Stack
A Queue serves its items in arrival order, and a Stack serves its items in reverse arrival order. Both store one type of item.
A queue serves the front first
Two names join the queue. Dequeue returns the name that arrived first.
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
Queue<string> line = new Queue<string>();
line.Enqueue("first");
line.Enqueue("second");
Console.WriteLine(line.Dequeue());
Console.WriteLine(line.Count);
}
}A stack serves the top first
Two names are pushed onto the stack. Pop returns the name pushed last.
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
Stack<string> pile = new Stack<string>();
pile.Push("bottom");
pile.Push("top");
Console.WriteLine(pile.Pop());
Console.WriteLine(pile.Count);
}
}Peek leaves the item in place
Peek reads the next item from each collection. Both counts stay at one after the reads.
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
Queue<string> line = new Queue<string>();
line.Enqueue("ticket");
Stack<string> pile = new Stack<string>();
pile.Push("page");
Console.WriteLine(line.Peek());
Console.WriteLine(pile.Peek());
Console.WriteLine(line.Count);
Console.WriteLine(pile.Count);
}
}Example
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
Queue<int> jobs = new Queue<int>();
jobs.Enqueue(10);
jobs.Enqueue(20);
jobs.Enqueue(30);
Console.WriteLine(jobs.Dequeue());
Console.WriteLine(jobs.Peek());
Console.WriteLine(jobs.Count);
}
}Key points
- Enqueue adds an item to the back of a queue.
- Dequeue removes and returns the front item.
- Push adds an item to the top of a stack.
- Pop removes and returns the top item.
- Peek returns the next item without removing it.
- Count reports how many items remain.
In this example, three job numbers join the queue in order. Dequeue removes and prints 10. Peek then shows 20 at the front, and Count reports the two jobs that remain.
Note
A queue is first in, first out. A stack is last in, first out.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
A stack receives 1, then 2, then 3. What does the first Pop return?