Queue and Stack
A Queue is a line at a shop where the first person in is served first, while a Stack is a pile of plates where the last one placed on top is taken first. Each has its own order for taking things out.
In this page:
Syntax
Queue<type> queue = new Queue<type>();
queue.Enqueue(item);
queue.Dequeue(); // first in, first out
Stack<type> stack = new Stack<type>();
stack.Push(item);
stack.Pop(); // last in, first out
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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Calling
PoporDequeueon an empty collection, which throwsInvalidOperationException. - Mixing up order: a stack is last in, first out and a queue is first in, first out.
- Using
Peekand expecting it to remove the item.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: