Queue and Stack
In this page:
Queue and Stack
Queue<T> is a first-in-first-out collection using Enqueue/Dequeue, while Stack<T> is last-in-first-out using Push/Pop. Queues model things like task processing order; stacks model things like undo history or recursive call tracking. Both throw an exception if you try to remove from an empty collection.
Note: Think "line at a store" for Queue and "plates stacked on top of each other" for Stack.
Example: Queue and Stack
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());
Stack<string> history = new Stack<string>();
history.Push("page1");
history.Push("page2");
Console.WriteLine(history.Pop());
}
}
Login to try C/C++/Java/PHP code in the editor
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: