Search⌘ K
AI Features

Stacks and Queues

Explore the principles of stacks and queues to control data processing order in programming. Learn how stacks implement last-in-first-out behavior, ideal for undo actions, while queues use first-in-first-out for handling tasks in sequence. Understand key methods like Push, Pop, Enqueue, and Dequeue with practical examples in C# generic collections.

In many programming scenarios, we do not need the flexibility to access data at random positions. Instead, we need strict control over the order in which items are processed. For example, consider the “Undo” feature in a text editor or the back button in a web browser. The most recent action must be the first one reversed. Alternatively, consider a background service handling incoming web requests or a printer managing print jobs. The first task to arrive must be the first one handled. To model these specific behaviors, .NET provides two specialized collections: stacks and queues.

Stacks

Stacks are a different way to approach collections. With arrays and lists, we can insert data and read it wherever we want. We can insert items in the middle and read from the end, for example. Stacks, however, only let us place and read new items on the top. The following illustration demonstrates this behavior:

Pushing an item onto a stack
Pushing an item onto a stack

Stacks behave like a group of items piled onto each other. We place new items on the top. When we want to read values, we start from the top and read items one by one until we reach the desired item.

This approach is ...