From the course: Programming Foundations: Data Structures

Unlock this course with a free trial

Join today to access over 25,300 courses taught by industry experts.

What is a stack?

What is a stack?

- [Narrator] Stacks are another type of container we can use to store our data. It's an ordered series of objects, just like a list, but its intended use is slightly different. With a stack, we push items onto the top and then pop them off in reverse order. Think of a stack of cards. Each card is stacked on top of the other. To remove a card, you take one off the top since removing from the bottom is impractical. When adding a card, it goes on top because adding to the bottom would require lifting the entire stack. This natural behavior gives stacks their defining feature. They follow a last-in, first-out, or LIFO principal. The most recently added item is the first to be removed, while the first item added stays at the bottom until everything above it has been removed. In practice, when we add to a stack, we say we push an item on. When we remove one, we pop it off. You can push as many items onto the stack as needed. But to access something further down, you must pop off everything…

Contents