Stacks and Queues

Understand how to implement and use the last-in-first-out Stack and first-in-first-out Queue data structures.

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: