Skip to content

Computer Science · Ch 3 — Stack

Stack

3.2

Stack

A stack is a linear arrangement of elements where all additions and removals happen from the same end — the top. Think of a pile of plates in a kitchen or a stack of books on a table (Figure 3.1). To put another book or plate on such a pile, we always place (add to the pile) the object at the top only. Likewise, to remove a book or a plate from such a pile, we always remove (delete from the pile) the object from the top only. This is because in a large pile, it is inconvenient — and often impossible — to add or remove an object from in between or from the bottom.

Such an arrangement of elements in a linear order is called a stack. We add new elements or remove existing elements from the same end, commonly referred to as the top of the stack. It thus follows the Last-In-First-Out (LIFO) principle: the element which was inserted last (the most recent element) will be the first one to be taken out from the stack. …

Figure 3.1Stack of plates and books
Fig. 3.1 — Stack of plates and books

Drawn by us to help you understand the concept clearly, and verified to make sure it's accurate. For exams, practice from your textbook's own diagram.

These two real-life examples give you the intuition behind a stack before we look at any code. A pile of plates on a shelf and a pile of books on a table both work the same way: you can only add a new plate or book on TOP of the pile, and you can only ever remove the one that's currently on top. You cannot pull a plate out from the middle of the stack without first removing everything above it. …