stack
Stacks: Definition, Array representation of stacks, Linked representation
of stacks, Stack as ADT, Arithmetic Expressions: Polish Notation,
Conversion of infix expression to postfix expression, Evaluation of
Postfix expression, Application of Stacks, Recursion, Towers of Hanoi,
Implementation of recursive procedures by stack. Queues: Definition,
Array representation of queue, Linked list representation of queues.
Types of queue: Simple queue, Circular queue, Double-ended queue,
Priority queue, Operations on Queues, Applications of queues.
Stacks
• A stack is a linear data structure in which elements are added and
removed according to the Last In, First Out (LIFO) principle. This
means the last element added to the stack is the first one to be
removed.
real life example of stack
1.Laundry Basket: The last clothes put in are the first to be taken out.
2.Library Books: The last book placed on a stack is the first to be picked up.
3.Web Browser Back Button: The last visited page is the first to return to when clicking back.
4.Undo in Text Editors: The most recent action is the first one undone.
5.Function Call Stack: The last called function is the first to finish.
6.Balanced Parentheses Checking: The last opened parenthesis must be closed first.
Features of a stack
• LIFO (Last In, First Out):
The last item added is the first one removed.
• Two Basic Operations:
Push adds an item, and
Pop removes the top item.
• Overflow and Underflow:
Overflow happens when the stack is full, and underflow occurs when it’s empty.
• Homogeneous Data Items:
All items in a stack are usually of the same type.
• Static or Dynamic Representation:
Stacks can have a fixed size (static) or grow/shrink (dynamic).
• Non-Primitive Data Structure:
It’s a complex structure made from primitive data types like integers or characters.
• Memory Efficiency:
Uses memory efficiently since it only requires space for active items.
• Fixed Access Point:
Data is only accessed from the top of the stack.
Push operations
Step 1: [overflow check]
if TOP = MAXSTK -1
then write (“stack overflow”)
return
Step 2: [increment TOP value]
TOP= TOP +1
Step 3: [insert the item at the TOP]
S[TOP]= item
Step 4: return
POP operation
Step 1: [underflow check]
if TOP= -1
write (“stack underflow”)
return
end if
Step 2: [delete the item]
item =s[TOP]
Step 3: [decrement TOP value]
TOP= TOP-1
Step 4: return
recursion
• Recursion is a process where a function calls itself to solve smaller subproblems of the original
problem until it reaches a stopping condition (called the base case).
• Syntax
return_type function_name(parameters) {
if (base_condition) {
// Return result when the base case is met
return value;
} else {
// Recursive call with modified parameters
return function_name(modified_parameters);
}
}
Tower of Hanoi
#include <stdio.h>
void towerOfHanoi(int n, char source, char destination, char auxiliary) {
if (n == 1) {
printf("Move disk 1 from %c to %cn", source, destination);
return;
}
towerOfHanoi(n - 1, source, auxiliary, destination);
printf("Move disk %d from %c to %cn", n, source, destination);
towerOfHanoi(n - 1, auxiliary, destination, source);
}
int main() {
int n;
printf("Enter the number of disks: ");
scanf("%d", &n);
towerOfHanoi(n, 'A', 'C', 'B');
return 0;
}
Factorial
#include <stdio.h>
int factorial(int n) {
if (n == 0) {
return 1; // Base case: 0! = 1
}
return n * factorial(n - 1); // Recursive call
}
int main() {
int num;
printf("Enter a non-negative integer: ");
scanf("%d", &num);
if (num < 0) {
printf("Factorial is not defined for negative numbers.n");
} else {
printf("Factorial of %d is: %dn", num, factorial(num));
}
return 0;
}
Arithmetic expressions
• arithmetic expressions can be represented in three different
notations: Infix, Prefix, and Postfix.
1. Infix Notation:
The operator is placed between the operands.
Example:
A + B
(5 * (2 + 3))
Operators like +, -, *, / are placed between numbers or variables.
Characteristics of Infix Notation
Operator Placement – Operators are placed between operands
(e.g., A + B).
Requires Parentheses – Parentheses are needed to control the order of
operations (e.g., (A + B) * C).
Relies on Precedence Rule – Operators follow precedence rules (e.g.,
multiplication * is evaluated before addition +).
Human-Friendly – It is the standard way of writing expressions and is easy to
read and understand.
2. Prefix Notation (Polish Notation)
• The operator is placed before the operands.
Example:
+ A B
• 5 + 2 3
No need for parentheses because the order of operations is
clear.Evaluate from right to left.
📌 Characteristics of Prefix (Polish) Notation
Operator Placement – Operators are placed before the operands (e.g., + A B).
No Parentheses – No need for parentheses because the order of operations is inherently clear.
Right to Left Evaluation – Expressions are evaluated from right to left, following operator
precedence.
Efficient for Computers – Easily processed by compilers and stack-based algorithms without
extra parsing.
Logical Structure – Provides a structured and unambiguous way to represent expressions.
3. Postfix Notation (Reverse Polish Notation)
• The operator is placed after the operands.
Example:
A B +
5 2 3 + *
No need for parentheses, the expression is evaluated as it is read.
Evaluate from left to right using a stack.
Characteristics of Postfix
Operator Placement – Operators are placed after the operands (e.g., A B +).
No Parentheses – No need for parentheses as the order of execution is inherently
defined.
Left to Right Evaluation – Expressions are evaluated from left to right, maintaining
natural execution flow.
Stack-Based Evaluation – Uses a stack to process expressions efficiently, making it
ideal for computers and calculators.
Applications of Stack
Recursion – Function calls are stored in a stack to track execution order and return values.
Reversal of String – Characters are pushed onto a stack and popped in reverse order.
Checking Parenthesis Matching – A stack is used to check if parentheses are balanced in an
expression.
Postfix Expression Evaluation – Operands are pushed, and operators pop and evaluate them in postfix
notation.
Infix to Postfix Conversion – A stack is used to convert infix expressions to postfix notation using
precedence rules.
Infix to Prefix Conversion – A stack is used to rearrange operators before operands in prefix notation.
Backtracking – Used in solving mazes, puzzles, and recursive algorithms to step back when needed.
Function Call Management – The system stack stores function calls and execution order in programs.
Undo Operations in Applications – Previous actions are stored in a stack to allow undo functionality.
Parsing in Compilers – Stacks help validate syntax and generate expression trees in compilers.
Browser Backtracking – The back button stores previously visited web pages in a stack for navigation.
Conclusion: Stacks are essential for managing data efficiently in various computing applications!
Advantages of Stack
Follows LIFO Technique – The last inserted element is removed first, making operations
simple and fast.
Efficient Memory Management – Uses a fixed memory area, reducing fragmentation and
making allocation faster.
Function Support – Helps in function calls, return values, and maintaining execution order.
Security and Reliability – Provides controlled access to data, reducing accidental overwrites or
leaks.
Ease of Implementation – Simple to implement using arrays or linked lists with basic
operations (push & pop).
Support for Recursive Algorithms – Stores recursive function calls automatically, managing
execution properly.
Ideal for Temporary Data – Perfect for storing temporary values like function variables,
expressions, and backtracking paths.
Disadvantages of stack
Limited Memory Size – Stacks have a fixed size, which limits how much data they can hold.
Fixed Size Requirement – In static stacks (arrays), the size must be predefined, which may lead
to wasted space or insufficient storage.
Stack Overflow Risk – If too many elements are pushed without enough space, it causes a stack
overflow error.
No Random Access – Unlike arrays, you can only access the top element, not elements in the
middle.
Difficult to Debug – Since data is removed in LIFO order, tracking errors in deep stacks can be
challenging.
Space Wastage – In some cases, unused memory in a stack remains allocated, leading to
inefficient memory usage.
Not Suitable for Large Datasets – Stacks are not ideal for handling large amounts of data due to
size limitations.
Sequential Access Limitations – You must access data in order (LIFO), which can be inefficient
for some tasks.
All searching and sorting techniques

stack and types of stack with algorithms and stack

  • 1.
  • 2.
    Stacks: Definition, Arrayrepresentation of stacks, Linked representation of stacks, Stack as ADT, Arithmetic Expressions: Polish Notation, Conversion of infix expression to postfix expression, Evaluation of Postfix expression, Application of Stacks, Recursion, Towers of Hanoi, Implementation of recursive procedures by stack. Queues: Definition, Array representation of queue, Linked list representation of queues. Types of queue: Simple queue, Circular queue, Double-ended queue, Priority queue, Operations on Queues, Applications of queues.
  • 3.
    Stacks • A stackis a linear data structure in which elements are added and removed according to the Last In, First Out (LIFO) principle. This means the last element added to the stack is the first one to be removed.
  • 4.
    real life exampleof stack 1.Laundry Basket: The last clothes put in are the first to be taken out. 2.Library Books: The last book placed on a stack is the first to be picked up. 3.Web Browser Back Button: The last visited page is the first to return to when clicking back. 4.Undo in Text Editors: The most recent action is the first one undone. 5.Function Call Stack: The last called function is the first to finish. 6.Balanced Parentheses Checking: The last opened parenthesis must be closed first.
  • 5.
    Features of astack • LIFO (Last In, First Out): The last item added is the first one removed. • Two Basic Operations: Push adds an item, and Pop removes the top item. • Overflow and Underflow: Overflow happens when the stack is full, and underflow occurs when it’s empty. • Homogeneous Data Items: All items in a stack are usually of the same type. • Static or Dynamic Representation: Stacks can have a fixed size (static) or grow/shrink (dynamic). • Non-Primitive Data Structure: It’s a complex structure made from primitive data types like integers or characters. • Memory Efficiency: Uses memory efficiently since it only requires space for active items. • Fixed Access Point: Data is only accessed from the top of the stack.
  • 6.
    Push operations Step 1:[overflow check] if TOP = MAXSTK -1 then write (“stack overflow”) return Step 2: [increment TOP value] TOP= TOP +1 Step 3: [insert the item at the TOP] S[TOP]= item Step 4: return
  • 7.
    POP operation Step 1:[underflow check] if TOP= -1 write (“stack underflow”) return end if Step 2: [delete the item] item =s[TOP] Step 3: [decrement TOP value] TOP= TOP-1 Step 4: return
  • 8.
    recursion • Recursion isa process where a function calls itself to solve smaller subproblems of the original problem until it reaches a stopping condition (called the base case). • Syntax return_type function_name(parameters) { if (base_condition) { // Return result when the base case is met return value; } else { // Recursive call with modified parameters return function_name(modified_parameters); } }
  • 9.
    Tower of Hanoi #include<stdio.h> void towerOfHanoi(int n, char source, char destination, char auxiliary) { if (n == 1) { printf("Move disk 1 from %c to %cn", source, destination); return; } towerOfHanoi(n - 1, source, auxiliary, destination); printf("Move disk %d from %c to %cn", n, source, destination); towerOfHanoi(n - 1, auxiliary, destination, source); } int main() { int n; printf("Enter the number of disks: "); scanf("%d", &n); towerOfHanoi(n, 'A', 'C', 'B'); return 0; }
  • 10.
    Factorial #include <stdio.h> int factorial(intn) { if (n == 0) { return 1; // Base case: 0! = 1 } return n * factorial(n - 1); // Recursive call } int main() { int num; printf("Enter a non-negative integer: "); scanf("%d", &num); if (num < 0) { printf("Factorial is not defined for negative numbers.n"); } else { printf("Factorial of %d is: %dn", num, factorial(num)); } return 0; }
  • 11.
    Arithmetic expressions • arithmeticexpressions can be represented in three different notations: Infix, Prefix, and Postfix. 1. Infix Notation: The operator is placed between the operands. Example: A + B (5 * (2 + 3)) Operators like +, -, *, / are placed between numbers or variables.
  • 12.
    Characteristics of InfixNotation Operator Placement – Operators are placed between operands (e.g., A + B). Requires Parentheses – Parentheses are needed to control the order of operations (e.g., (A + B) * C). Relies on Precedence Rule – Operators follow precedence rules (e.g., multiplication * is evaluated before addition +). Human-Friendly – It is the standard way of writing expressions and is easy to read and understand.
  • 13.
    2. Prefix Notation(Polish Notation) • The operator is placed before the operands. Example: + A B • 5 + 2 3 No need for parentheses because the order of operations is clear.Evaluate from right to left.
  • 14.
    📌 Characteristics ofPrefix (Polish) Notation Operator Placement – Operators are placed before the operands (e.g., + A B). No Parentheses – No need for parentheses because the order of operations is inherently clear. Right to Left Evaluation – Expressions are evaluated from right to left, following operator precedence. Efficient for Computers – Easily processed by compilers and stack-based algorithms without extra parsing. Logical Structure – Provides a structured and unambiguous way to represent expressions.
  • 15.
    3. Postfix Notation(Reverse Polish Notation) • The operator is placed after the operands. Example: A B + 5 2 3 + * No need for parentheses, the expression is evaluated as it is read. Evaluate from left to right using a stack.
  • 16.
    Characteristics of Postfix OperatorPlacement – Operators are placed after the operands (e.g., A B +). No Parentheses – No need for parentheses as the order of execution is inherently defined. Left to Right Evaluation – Expressions are evaluated from left to right, maintaining natural execution flow. Stack-Based Evaluation – Uses a stack to process expressions efficiently, making it ideal for computers and calculators.
  • 17.
    Applications of Stack Recursion– Function calls are stored in a stack to track execution order and return values. Reversal of String – Characters are pushed onto a stack and popped in reverse order. Checking Parenthesis Matching – A stack is used to check if parentheses are balanced in an expression. Postfix Expression Evaluation – Operands are pushed, and operators pop and evaluate them in postfix notation. Infix to Postfix Conversion – A stack is used to convert infix expressions to postfix notation using precedence rules. Infix to Prefix Conversion – A stack is used to rearrange operators before operands in prefix notation. Backtracking – Used in solving mazes, puzzles, and recursive algorithms to step back when needed. Function Call Management – The system stack stores function calls and execution order in programs. Undo Operations in Applications – Previous actions are stored in a stack to allow undo functionality. Parsing in Compilers – Stacks help validate syntax and generate expression trees in compilers. Browser Backtracking – The back button stores previously visited web pages in a stack for navigation. Conclusion: Stacks are essential for managing data efficiently in various computing applications!
  • 18.
    Advantages of Stack FollowsLIFO Technique – The last inserted element is removed first, making operations simple and fast. Efficient Memory Management – Uses a fixed memory area, reducing fragmentation and making allocation faster. Function Support – Helps in function calls, return values, and maintaining execution order. Security and Reliability – Provides controlled access to data, reducing accidental overwrites or leaks. Ease of Implementation – Simple to implement using arrays or linked lists with basic operations (push & pop). Support for Recursive Algorithms – Stores recursive function calls automatically, managing execution properly. Ideal for Temporary Data – Perfect for storing temporary values like function variables, expressions, and backtracking paths.
  • 19.
    Disadvantages of stack LimitedMemory Size – Stacks have a fixed size, which limits how much data they can hold. Fixed Size Requirement – In static stacks (arrays), the size must be predefined, which may lead to wasted space or insufficient storage. Stack Overflow Risk – If too many elements are pushed without enough space, it causes a stack overflow error. No Random Access – Unlike arrays, you can only access the top element, not elements in the middle. Difficult to Debug – Since data is removed in LIFO order, tracking errors in deep stacks can be challenging. Space Wastage – In some cases, unused memory in a stack remains allocated, leading to inefficient memory usage. Not Suitable for Large Datasets – Stacks are not ideal for handling large amounts of data due to size limitations. Sequential Access Limitations – You must access data in order (LIFO), which can be inefficient for some tasks.
  • 20.
    All searching andsorting techniques