

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!


A Stack is a linear data structure that follows a strict order in which operations are performed. This order is known as LIFO (Last-In, First-Out). In a LIFO data structure, the most recently added element is the first one to be removed.
REAL-WORLD ANALOGY Think of a stack of plates at a buffet. When clean plates are brought out, they are placed on top of the stack. When a person needs a plate, they take the one off the top. The last plate placed on the stack is the first one taken off.
A stack supports several primary operations to interact with its stored data. Because access is restricted to only one end (the "top"), these operations are highly efficient.
Operation Description TimeComplexity
push(item) Adds a new element to the top of the stack. O(1)
pop() Removes and returns the top element from the stack. O(1)
peek() / top() Returns the top element without modifying the stack. O(1)
isEmpty() Checks if the stack has no elements. O(1)
isFull() Checks if the stack has reached its maximumcapacity. O(1)
3. Implementation Strategies
Stacks are abstract data types; they define a behavior rather than a strict structural implementation. They are typically implemented using one of the following underlying data structures:
Uses a fixed-size or dynamic array. A pointer or index variable (usually called top ) tracks the position of the last inserted element.
Advantages: Simple to implement. Memory efficient because it doesn't require extra pointers. Cache-friendly due to contiguous memory allocation. Disadvantages: Fixed capacity (unless a dynamic array is used, which incurs O(N) reallocation cost). Can lead to Stack Overflow if the array bounds are exceeded.
Uses a singly linked list. The head of the list functions as the top of the stack. Pushing an item means inserting it at the head, and popping means removing the head node.
Advantages: Dynamic size. It can grow and shrink organically as needed without pre- allocating large chunks of memory. No risk of stack overflow (unless the system runs out of heap memory). Disadvantages: Requires extra memory for storing node pointers. Slightly slower access times due to scattered memory locations (not cache-friendly).
4. Key Applications in Computer Science
Stacks are incredibly versatile and serve as the backbone for many algorithms and system-level operations:
Function Call Stack: Operating systems and programming language runtimes use stacks to manage active subroutines, handle recursion, and store local variables.