Stacks and Applications
Stacks and Applications
pop
create
STACK
isempty
isfull
STACK: Last-In-First-Out (LIFO)
• void push (stack *s, int element);
/* Insert an element in the stack */
• int pop (stack *s);
/* Remove and return the top element */
• void create (stack *s);
/* Create a new stack */
• int isempty (stack *s);
/* Check if stack is empty */
• int isfull (stack *s);
/* Check if stack is full */
PUSH
top
top
Pop using Stack
POP
top
top
Stack using Linked List
Push using Linked List
PUSH OPERATION
top
Pop using Linked List
POP OPERATION
top
Basic Idea
• In the array implementation, we would:
• Declare an array of fixed size (which determines the maximum size of the
stack)
• Keep a variable which always points to the “top” of the stack.
• Contains the array index of the “top” element.
Operations Complexity
push() O(1)
pop() O(1)
isEmpty() O(1)
size() O(1)
Stack in C++ STL
Stack-Pair in STL
Stack in STL Stacks are a type of container adaptors with LIFO(Last In First Out)
type of working, where a new element is added at one end and (top) an element
is removed from that end only.
Pair in STL The pair container is a simple container defined in header consisting of
two data elements or objects. The first element is referenced as ‘first’ and the
second element as ‘second’ and the order is fixed (first, second).
Design a stack that supports getMin() in O(1) time and O(1)
extra space
int mini(int a, int b) { return a > b ? b : a; }
class MinStack {
public:
stack<pair<int, int> > s;
Stack size estimation is process of determining the amount of memory allocated to the call stack for a particular
program or thread. The call stack is a region of memory that operates on a Last In, First Out (LIFO) basis and is
used for managing function calls and local variables.
Recursion: Recursive functions can lead to a significant increase in the stack size, as each recursive call adds a new
stack frame. The depth of recursion directly impacts the stack size required.
Local Variables: The size of local variables within functions contributes to the overall stack size. Larger local variables or
arrays can consume more stack space.
Thread Stack Size: In a multithreaded program, each thread typically has its own stack. The stack size for each thread is
specified during thread creation. Estimating the required stack size is crucial to prevent stack
overflow.
Operating System Limits: Operating systems often impose limits on the maximum stack size for a thread. Exceeding
these limits can result in a stack overflow, leading to program termination.
Static Analysis and Tools: Some programming languages provide static analysis tools that can estimate the stack size
requirements based on the code structure and function calls.
Platform and Compiler Considerations: Stack size can vary across different platforms and compilers. It's important for
Any question?