In computing, a stack is a data structure used to store a collection of objects. Individual items can be added and stored in a stack using a push operation. Objects can be retrieved using a pop operation, which removes an item from the stack.
When an object is added to a stack, it is placed on the top of all previously entered items. When an item is removed, it can either be removed from the top or bottom of the stack. A stack in which items are removed the top is considered a “LIFO” (Last In, First Out) stack. You can picture a LIFO stack as a deck of cards where you lay individual cards on the deck, then draw cards from the top. In a “FIFO” (First In, First Out) stack, items are removed the bottom. You can picture a FIFO stack as a row in a vending machine where items are dispensed in the order they were placed in the machine.
Stacks have several applications in commuter programming. LIFO stacks, for example, can be used to retrieve recently used objects, from a cache. FIFO stacks may be used to ensure data is retrieved in the order it was entered, which may be used for processing data in a queue.
While stacks are commonly used by software programmers, you will typically not notice them while using a program. This is because the creation of stacks and push and pop operations are performed in the background while an application is running and are not visible to the user. However, if a stack runs out of memory, it will cause a “stack overflow.” If not handled correctly by the program, a stack overflow may generate an error message or cause the program to crash.
NOTE: The term “stack” may also refer to a protocol stack, which consists of multiple network protocols that work together. Each protocol is categorized into one of seven different layers defined in the OSI model.