Data Structures & Algorithm : Unit 2
1
Stack and its Operations
Implementation of Stack
2
Stack
Stack is a linear data structure
Follows the LIFO (Last In First Out) principle : Last element inserted into the stack is the first
element to be removed
Behaves like a stack of plates, stack of books
3
Operations of Stack
Push
Pop
Peek
IsEmpty
IsFull
4
Operations on Stack
Push (Insertion)
Adds an element to the top of the stack.
If the stack is already full , it’s called Stack Overflow
Pop (Deletion)
Removes the element from the top of the stack
If the stack is empty, it’s called Stack Underflow.
5
Peek
Returns the top element of the stack without removing it.
IsEmpty( )
Checks if the stack is empty.
Returns true if empty, else false
IsFull( )
Checks if the stack is full
Useful when stack is implemented using arrays with fixed size.
6
Stack Representation / Implementation
Using Arrays
Using Linked List
7
Stack Using Arrays /Linked List
8
Working of Stack Data Structure (Using Array )
TOP variable is used to keep track of the top data in the stack.
Initialize TOP = -1 . It means stack is empty
PUSH Operation : Increment TOP by 1 and add new data on TOP index
POP Operation :Return the data on TOP index and decrement TOP by 1
Before PUSH operation , check if the stack is already full
Before POP operation , check if the stack is already empty
9
10
Algorithm of PUSH Operation
STACK[MAX] : Array of size MAX to represent stack 1.Start
2. If TOP == MAX - 1 then
TOP : Pointer (index) to the top of the stack
Print "Stack Overflow"
ITEM : Element to be inserted
Go to Step 6
3. Set TOP = TOP + 1
4. Set STACK[TOP] = ITEM
5. Print "ITEM Inserted Successfully"
6. End
11
Complexity Analysis of PUSH Operation
Array Implementation of Stack :
Time Complexity: O(1) (direct access using index)
Space Complexity : O(1)
Linked List Implementation of Stack:
Insert new node at head
Time Complexity: O(1)
Space Complexity : O(1)
12
Algorithm of POP Operation
STACK[MAX] : Array of size MAX to represent stack 1. Start
TOP : Pointer (index) to the top of the stack 2. If TOP == -1 then
Print "Stack Underflow"
ITEM : Element to be deleted
Go to Step 6
3. Set ITEM = STACK[TOP]
4. Set TOP = TOP - 1
5. Print "ITEM Deleted Successfully"
6. End
13
Complexity Analysis of POP Operation
Array Implementation of Stack :
Time Complexity: O(1) (just decrement top index)
Space Complexity : O(1)
Linked List Implementation of Stack:
Remove node from head
Time Complexity: O(1)
Space Complexity : O(1)
14
Algorithm for Peek Operation
STACK[MAX] : array to represent stack 1.Start
TOP : pointer (index) to the top of stack 2. If TOP == -1 then
ITEM : element at the top Print "Stack is Empty"
Go to Step 5
3. Set ITEM = STACK[TOP]
4. Print "Top element is ITEM"
5. End
15
Complexity Analysis of Peek Operation
Returns the element at the top without removing it
Time Complexity: O(1)
Space Complexity: O(1)
16
Algorithm fo isEmpty( ) Operation
STACK[MAX] : array to represent stack 1.Start
TOP : pointer (index) to the top of stack 2. If TOP == -1 then
Print "Stack is Empty"
Return TRUE
3. Print "Stack is Not Empty"
Return FALSE
4. End
17
Algorithm for isFull( ) Operation
STACK[MAX] : array to represent stack 1.Start
TOP : pointer (index) to the top of stack 2. If TOP == MAX - 1 then
MAX : maximum size of stack Print "Stack is Full "
Return TRUE
3. Print "Stack is Not Full"
Return FALSE
4. End
18
isEmpty Operation
Check if stack has zero elements.
Time Complexity: O(1)
Space Complexity: O(1)
isFull Operation (only for array-based stack)
Check if top has reached maximum size
Time Complexity: O(1)
Space Complexity: O(1)
19
Implementation of Stack
Use of Array and TOP variable
#define MAX 10
struct stack
{
int items[MAX];
int top;
};
typedef struct stack s;
20
Built in Data Types
Built-in Data Types
These are the predefined data types provided by the programming language
They are already available and can be used directly without any extra definition
Example int ,float , double , char , void
21
User-defined Data Types
User-defined data types are created by the programmer to represent complex data.
They are built using C’s features like struct, union, typedef, enum
struct (Structure)
Used to group variables of different data types under one name
In a structure, each member has its own memory
struct Student
{ Student is a user-defined type
int id;
char name[20];
float marks;
};
22
#include <stdio.h>
printf(" Roll No : %d\n", s1.rollno);
struct Student {
printf("Name: %s\n", s1.name);
int rollno;
printf("Marks: %.2f \n", s1.marks);
char name[20];
return 0;
float marks;
}
};
int main( ) {
struct Student s1;
printf("Enter student Roll No. ");
scanf("%d", &s1.rollno);
printf("Enter student name: ");
scanf("%s", s1.name);
printf("Enter student marks: ");
scanf("%f", &s1.marks); 23
union
A union in C is a user-defined data type
In a union, all members share the same memory location.
More memory-efficient, but only one member can be used at a time
Only one member can store a valid value at a time.
The size of a union is equal to the size of its largest member
union Data
{
int i;
float f;
char c;
};
24
typedef (Type Definition / Alias)
Used to create a new name (alias) for an existing data type
Example
typedef unsigned int uint;
uint age = 25;
typedef struct student s;
25
Application of Stack
Expression Evaluation
Stacks are used to evaluate expressions written in postfix (Reverse Polish Notation) or to
convert infix to postfix/prefix.
Example: Evaluating 3 4 * 5 + using stack gives result 17.
Function Calls (Recursion)
Each function call stores its return address and local variables in a call stack.
When the function ends, the stack helps return to the correct point in the program.
Application of Stack
Undo/Redo Operations
Text editors (like MS Word) use stacks to store previous states
Undo pops the last action, and Redo re-applies it.
Browser Navigation (Forward/Backward)
When you go to a new webpage, the current page is pushed onto a stack.
Pressing Back pops from the stack to return to the previous page.
Application of Stack
Parentheses Matching
Used in compilers to check balanced brackets { [ ( ) ] }
Push opening brackets onto stack, pop when closing brackets are found.
String Reversal
A stack can be used to reverse a string
Each character is pushed onto the stack, then popped out one by one to form the reversed
string.
Example: "HELLO" → push all → pop → "OLLEH".
Application of Stack
Backtracking Algorithms
Problems like maze solving, puzzle solving, and DFS in graphs use stacks to remember
previous choices and backtrack when needed.
Depth First Search (DFS) uses a stack to keep track of vertices to be explored
Arithmetic Expression
An arithmetic expression is a combination of :
Operands : numbers or variables (e.g., 3, x, y)
Operators : + , - , * , / , ^
Parentheses : ( ) used to group terms
Parentheses or some operator-precedence convention are used to change the order of
operators and
operands in an arithmetic expression
Types of Arithmetic Expressions
Infix Expression
Prefix Expression ( Polish Notation )
Postfix Expression ( Reverse Polish Notation )
Types of Arithmetic Expressions
Infix Expression
Operator is between operands . Example: A + B , ( A + B ) * C
Natural for humans, but hard for computers to evaluate directly.
Postfix Expression (Reverse Polish Notation)
Operator is written after operands. Example: A B + , AB+C*
Easy for computers to evaluate using stack.
Prefix Expression (Polish Notation)
Operator is written before operands. Example: + A B , *+ABC
Also stack-friendly.
Evaluation of Arithmetic Expression
Precedence for Binary operators
Highest : Exponentiation (^)
Next highest : Multiplication (*) and division (/)
Lowest : Addition (+) and Subtraction (-)
Associativity of Operators : ^ is right-to-left, others are left-to-right.
Arithmetic expressions are best evaluated using stacks
Stack helps in handling precedence , parentheses and evaluation order
Evaluation of Arithmetic Expression
Infix Expression must be converted to the Postfix notation.
Conversion from infix expression to postfix expression must consider hierarchy of operators
Computer uses stack to evaluate postfix expression
Example of Infix to Postfix Expression
Example 1 : Convert Infix to Postfix Example 2 : Convert Infix to Postfix
Infix notation : A + B * C + D Infix notation : A * B + C * D
Postfix Notation : A B C * + D + Postfix Notation : A B * C D * +
Example 3 : Convert Infix to Postfix
Infix notation : A * (B + C) / D
Postfix Notation : ABC+*D/
Example of Infix to Postfix Expression
Example 4 : Convert infix to Postfix Example 6 : Convert Infix to Postfix
Infix notation: (A-B)*[C/(D+E)+F] Infix notation : (A * B)+( C /D) -E
Post-fix notation: AB- CDE +/F +* Postfix Notation : AB*CD/+E-
Example 5 : Convert Infix to Postfix
Infix : ((A + B) – C * (D / E)) + F
Postfix: AB+CDE/*-F+
Example of Infix to Prefix Expression
Example 1 : Convert Infix to Prefix
Infix notation : A * B + C * D
Pre-fix Notation : + * A B * C D
Example 2 : Convert Infix to Prefix
Infix notation : A + B * C + D
Pre-fix Notation : + + A * B C D
Example of Infix to Prefix Expression
Example 3 : Convert Infix to Prefix
Infix notation : A *(B + C) / D
Pre-fix Notation : /*A+BCD
Example 4 : Convert Infix to Prefix
Infix notation : (A * B)+( C /D) -E
Prefix Notation : -+*AB/CDE
Evaluation of Postfix Expression using Stack
Evaluate Postfix Expression : 2 , 3 , 4 , * , +
Evaluate Postfix Expression : 2,10,+,9,6, - , /
Algorithm for Postfix Evaluation
1. Start
2. Initialize empty stack.
3. Scan Postfix expression from left to right.
4. If operand scanned :
a) Push it onto the stack
5. If operator ‘’op’ scanned:
a) Pop the top two operands a (first popped), b (second popped) from the stack.
b) Compute b op a
c) Push the result back onto the stack.
6. Repeat steps 3–5 until the entire postfix expression is scanned.
7. Value left in the stack is the result of Postfix expression
8.End
Algorithm Infix to Postfix
1. Start d) if operator scanned :
2. Initialize an empty stack for operators While stack is not empty and
Precedence(Operator on top of stack) ≥
3. Scan the infix expression from left to right.
Precedence(Current operator) :
4. For each symbol scanned :
i) Pop operator from stack and add to postfix
a) If operand scanned : expression.
Add it directly to the postfix expression. ii)Push the current operator onto the stack.
b) If ‘ ( ’ scanned: Push it onto the stack. 5. After scanning the entire infix expression :
c) If ‘ ) ’ scanned: Pop from the stack and add to i) Pop all remaining operators from the stack
postfix until ‘ ( ’ is found. and add them to postfix
Remove the ‘ ( ’ from stack 6. End
Convert Infix a+b*c+d to Postfix
Convert Infix ((A + B) – C * (D / E)) + F to Postfix
Infix to Postfix Expression
Example 1 : Convert Infix Expression ((A + B) – C * (D / E)) + F to to Postfix Expression
AB+CDE/*-F+
Example 2 : Convert Infix expression: K + L - M*N + (O^P) * W/U/V * T + Q to Postfix Expression
KL+MN*-OP^W*U/V/T*+Q+
Example 3 : Convert Infix expression a+b*(c^d-e)^(f+g*h)-i to Postfix Expression
abcd^e–fgh*+^*+i-
Infix to Prefix Expression
Algorithm Infix to Prefix Expression
1. Start
2. Reverse the given infix expression
i)While reversing, replace ( with ) and ) with (
3. Convert the reversed expression into postfix using the Infix to Postfix algorithm.
4.Reverse the postfix expression obtained.
5.Result is the Prefix expression.
6. End
Convert Infix a+( b*c ) +d to Prefix
Postfix : dcb*+a+
Reverse : +a+*bcd
Prefix Expression : +a+*bcd
Infix Expression to Prefix Expression using Stack
Convert infix expression ( (A + B) * (C – D) ) / E to Prefix expression
/*+AB-CDE
Convert Infix expression (A - B) / (C + D * E) to Prefix expression
/ -AB+ C* DE
PYQ from Unit 2
Describe Stack
What is Stack ? How stack can be represented in memory ? Describe three application of stack .
Explain different application of stack.
What is stack? Write algorithm for implementation of stack.
What is Stack ? Write array implementation of stack. Write algorithms for various operations that
can be performed on stack.
Write algorithm to convert infix expression to postfix expression. Apply your algorithm on the
following infix expression A + ( B*C - ( D / E ^ F ) * G ) * H
What do you understand by Prefix and Postfix evaluation . Explain the conversion method from
infix to prefix and postfix expression. Mention the Prefix and Postfix expression for the following
infix expression using stack A + B * ( C + D ) / F + D * E
What is Stack ? Give static implementation of Stack with PUSH and POP algorithms