Stack Data Structure

The stack data structure is a fundamental abstract data type commonly used in computer science and software engineering. It follows the Last-In, First-Out (LIFO) principle, meaning that the last element added to the stack is the first one to be removed. Think of it like a stack of plates: you can only add or remove plates from the top of the stack.

Stack of pancakes
Stack of pancakes

Basic Operations

Implementations

A stack implemented using an array

A stack implemented using a Linked List.

Time Complexity

Array Implementation

For the list/array/vector implementation of the stack the average time complexity of the push and pop operations are O(1). However, if the array needs to be resized the complexity will become O(n) where n is the number of elements in the stack.

Linked List Implementation

A summarization of the best, average, and worst-case time and space complexities for common operations on the stack data structure using a linked list:

OperationBest CaseAverage CaseWorst CaseSpace Complexity
Push(O(1))(O(1))(O(1))(O(1))
Pop(O(1))(O(1))(O(1))(O(1))
Peek(O(1))(O(1))(O(1))(O(1))
isEmpty(O(1))(O(1))(O(1))(O(1))
Size(O(1)) or (O(n))(O(1)) or (O(n))(O(1)) or (O(n))(O(1)) or (O(n))

Explanation:

In summary, stack operations are typically very efficient, with constant time complexities for basic operations like Push, Pop, Peek, and isEmpty. The space complexity depends on the underlying implementation and whether the size of the stack is maintained explicitly.

Applications of Stack Data Structure

A stack is a simple but very powerful data structure and has many uses. Some of those uses are:

Challenges