2. Data structure :
• A data structure is a way of organizing and storing data in a
computer so that it can be accessed and modified efficiently. It
provides a systematic way to manage and manipulate data, making
it easier to perform operations like searching, sorting, and
inserting.
• Types of Datastructures:
• 1.Linear Datastructure
• 2.Non Linear DataStructure
23-03-2024 M SUNITHA 2
3. Linear Data Structures:
• In a linear data structure, data elements are arranged sequentially or
linearly.
• Each element is attached to its previous and next adjacent element.
• These structures involve single levels.
• Traversing all the elements can be done in a single run.
• Examples of linear data structures include:
• Array: Stores elements of the same type with positive indices.
• Stack: Follows the LIFO (Last In-First Out) rule.
• Queue: Follows the FIFO (First In-First Out) rule.
• Linked List: Consists of nodes with data and pointers.
23-03-2024 M SUNITHA 3
6. Non-linear Data Structures:
• Non-linear Data Structures:
• In non-linear data structures, data elements are not arranged
sequentially.
• These structures are hierarchical and can exist on multiple
levels.
• Examples of non-linear data structures include:
• Trees: Hierarchical structures with nodes connected by edges.
• Graphs: Consist of vertices (nodes) and edges connecting them.
• Heaps: Used for efficient priority queue operations.
• Tries: Used for efficient string matching and storage.
• Sparse Matrices: Represent matrices with mostly zero values.
• B-trees: Used for efficient database indexing.
23-03-2024 M SUNITHA 6
7. Linear Data Structures:
1.Array
A collection of elements of the same data type stored in contiguous memory
locations.
Accessed using an index (starting from 0).
Useful for storing fixed-size data.
Example: int myArray[5];
2.Linked Lists:
A dynamic data structure where elements (nodes) are connected using
pointers.
Each node contains data and a pointer to the next node.
Useful for dynamic memory allocation.
23-03-2024 M SUNITHA 7
8. Linear Data Structures:
1.Stacks:
1.Follows the LIFO (Last In, First Out) principle.
2.Elements are added and removed from the same end (top).
3.Common operations: push (add) and pop (remove).
2.Queues:
1.Follows the FIFO (First In, First Out) principle.
2.Elements are added at the rear and removed from the front.
3.Common operations: enqueue (add) and dequeue (remove).
23-03-2024 M SUNITHA 8
9. Non Linear DataStructures:
1.Trees:
1.Hierarchical data structures with a root node and child nodes.
2.Common types: Binary Trees, Binary Search Trees, and AVL Trees.
3.Useful for representing hierarchical relationships.
2.Graphs:
1.Consist of nodes (vertices) and edges connecting them.
2.Used to represent complex relationships.
3.Types: Directed Graphs, Undirected Graphs, and Weighted
Graphs.
23-03-2024 M SUNITHA 9
10. Stack:
• A stack is a linear data structure in which the insertion of a new element and removal of
an existing element takes place at the same end represented as the top of the stack.
• Types of Stacks:
• Fixed Size Stack: As the name suggests, a fixed size stack has a fixed size and cannot
grow or shrink dynamically. If the stack is full and an attempt is made to add an element
to it, an overflow error occurs. If the stack is empty and an attempt is made to remove an
element from it, an underflow error occurs.
• Dynamic Size Stack: A dynamic size stack can grow or shrink dynamically. When the
stack is full, it automatically increases its size to accommodate the new element, and
when the stack is empty, it decreases its size. This type of stack is implemented using a
linked list, as it allows for easy resizing of the stack.
23-03-2024 M SUNITHA 10
11. Core Operations:
1.Core Operations:
1.Push: Adds an item to the top of the stack.
2.Pop: Removes the top item from the stack.
3.Peek/Top: Retrieves the top item without removing it.
4.isEmpty: Checks if the stack is empty.
23-03-2024 M SUNITHA 11
12. Applications of Stacks
1.Reversing Strings: Stacks can reverse the order of characters in a string.
2.Expression Evaluation: Stacks help validate expressions (e.g., checking
balanced parentheses).
3.Postfix Conversion: Stacks convert infix expressions to postfix notation.
4.Backtracking Algorithms: Stacks are used in backtracking algorithms
like DFS (Depth-First Search).
23-03-2024 M SUNITHA 12
13. Examples of Stacks in Real Life
1.Examples of Stacks in Real Life:
1.Browser History: The back button maintains a stack of visited pages.
2.Function Calls: Function calls are managed using a call stack.
3.Undo/Redo Operations: Stacks store previous states for undo/redo
functionality.
23-03-2024 M SUNITHA 13
14. Array Representation of a Stack
•In an array-based stack, we use a fixed-size array to store elements.
•The top of the stack is represented by an index (usually called top).
•When an element is pushed, it is added to the array at
the top position.
•When an element is popped, it is removed from the top position.
•Here’s a visual representation:
23-03-2024 M SUNITHA 14
15. Linked List Representation of a Stack:
•In a linked list-based stack, we use a linked list to store elements.
•Each node in the linked list represents an element.
•The top points to the first node (top of the stack).
•When an element is pushed, a new node is added to the front of the linked list.
•When an element is poppednode is removed.
•Here’s a visual representation:
•, the first
23-03-2024 M SUNITHA 15
21. Key Characteristics of a Stack:
• LIFO (Last In First Out): The last element inserted into the
stack is the first one to be removed.
• FILO (First In Last Out): The first element inserted remains at
the bottom, and subsequent elements stack on top of it.
23-03-2024 M SUNITHA 21
22. Algorithms for Stack Operations
1.Push:
•If the stack is full, it’s an overflow condition.
•Otherwise, increment the top index and assign the value to the new element.
•Algorithm:
push(item):
if stack is full: return Overflow
else:
increment top stack[top] = item
void push(int val, int n) {
if (top == n) {
printf("nOverflow"); // Stack is full
} else {
top = top + 1;
stack[top] = val;
}
}
23-03-2024 M SUNITHA 22
23. • Pop:
• If the stack is empty, it’s an underflow condition.
• Otherwise, return the value of the top element and decrement the top index.
• Pop():
• if stack is empty:
• return Underflow
• else:
• value = stack[top]
• decrement top
• return value
int pop() {
if (top == -1) {
printf("nUnderflow"); // Stack is empty
return 0;
} else {
return stack[top--];
}
}
23-03-2024 M SUNITHA 23
24. • Top.( Peek Operation (Viewing the Top Element)
• Returns the top element without removing it.
• Algoritham:
• top():
• return stack[top]
int peek() {
if (top == -1) {
printf("nUnderflow"); // Stack is empty
return 0;
} else {
return stack[top];
}
}
• isEmpty:
• Returns true if the stack is empty, else false.
• Algorithm
23-03-2024 M SUNITHA 24
26. Application of Stacks:
1.Evaluation of Arithmetic Expressions:
1.A stack is a powerful tool for evaluating arithmetic expressions in
programming languages. It handles operands, operators, and
parentheses efficiently.
2.Arithmetic expressions can be represented in three notations:
1.Infix Notation: Operators are placed between operands (e.g., A + B).
2.Prefix Notation (Polish Notation): Operators precede operands (e.g., + A B).
3.Postfix Notation (Reverse Polish Notation): Operators follow operands (e.g.,
AB +).
3.The stack helps convert expressions between these notations and
evaluate them based on precedence rules.
23-03-2024 M SUNITHA 26
27. Application of Stacks:
1.Reverse a Data:
1.Stacks can reverse data efficiently.
2.For instance, reversing a string or a sequence of elements.
2.Function Calls:
1.Function calls are managed using stacks.
2.When a function is called, its context (variables, return address) is
pushed onto the stack.
3.Upon returning, the context is popped, restoring the previous state.
23-03-2024 M SUNITHA 27
29. Infix expression and Postfix expression
• Infix expression: The expression of the form “a operator b” (a + b) i.e., when
an operator is in-between every pair of operands.
Syntax: <operand><operator><operand> i.e. an <operator> is preceded
and succeeded by an <operand>. Such an expression is termed infix
expression. E.g., A+B
Postfix expression: The expression of the form “a b operator” (ab+) i.e.,
When every pair of operands is followed by an operator.
Syntax:operand><operand><operator>
• Input: A + B * C + D
Output: ABC*+D+
23-03-2024 M SUNITHA 29
30. Infix To Postfix Conversion:
1.Scan the infix expression from left to right.
2.If the scanned character is an operand, put it in the postfix expression.
Otherwise, do the following
3.If the precedence and associativity of the scanned operator are greater than
the precedence and associativity of the operator in the stack [or the stack is
empty or the stack contains a ‘(‘ ], then push it in the stack. [‘^‘ operator is
right associative and other operators like ‘+‘,’–‘,’*‘ and ‘/‘ are left-
associative].
Check especially for a condition when the operator at the top of the stack and
the scanned operator both are ‘^‘. In this condition, the precedence of the
scanned operator is higher due to its right associativity. So it will be pushed
into the operator stack.
In all the other cases when the top of the operator stack is the same as the
scanned operator, then pop the operator from the stack because of left
associativity due to which the scanned operator has less precedence.
Else, Pop all the operators from the stack which are greater than or equal to in
precedence than that of the scanned operator.
After doing that Push the scanned operator to the stack. (If you encounter
parenthesis while popping then stop there and push the scanned operator in the
stack.)
4.If the scanned character is a ‘(‘, push it to the stack.
5.If the scanned character is a ‘)’, pop the stack and output it until a ‘(‘ is
encountered, and discard both the parenthesis.
6.Repeat steps 2-5 until the infix expression is scanned.
7.Once the scanning is over, Pop the stack and add the operators in the postfix
23-03-2024 M SUNITHA 30
31. Infix to Postfix Conversion Algorithm
1.Initialize an empty stack to hold operators.
2.Scan the infix expression from left to right.
3.For each character in the infix expression:
1. If it’s an operand (a variable or a constant), add it directly to the postfix
expression.
2. If it’s an operator or parenthesis:
1.If the stack is empty or the top of the stack contains an opening parenthesis
‘(’, push the current operator onto the stack.
2.Otherwise, compare the precedence of the current operator with the
operator at the top of the stack:
1.If the current operator has higher precedence, push it onto the stack.
2.If the current operator has lower or equal precedence, pop operators
from the stack and add them to the postfix expression until the stack is
empty or an opening parenthesis is encountered. Then push the current
operator onto the stack.
3.When encountering a closing parenthesis ‘)’, pop operators from the stack
and add them to the postfix expression until an opening parenthesis ‘(’ is
encountered. Discard both parentheses.
4.After scanning the entire infix expression, pop any remaining operators from the
stack and add them to the postfix expression.
23-03-2024 M SUNITHA 31
32. Example:
• Example:
• Let’s convert the infix expression “(A + B) * C” to postfix:
1.Initialize an empty stack.
2.Scan the expression from left to right:
1.‘(’: Push onto the stack.
2.‘A’: Add to the postfix expression.
3.‘+’: Push onto the stack.
4.‘B’: Add to the postfix expression.
5.‘)’: Pop ‘+’ from the stack and add it to the postfix expression.
6.‘*’: Push ‘*’ onto the stack.
7.‘C’: Add to the postfix expression.
3.Pop ‘*’ from the stack and add it to the postfix expression.
4.The final postfix expression is "AB+C"*.
23-03-2024 M SUNITHA 32
33. Infix Expression to Postfix
Expression:
• infix expression to a postfix expression. This time, we’ll use the expression: (A + B) * C - D
/ E.
• (A + B) * C - D / E.
1.Infix expression: (A + B) * C - D / E
• Now, let’s apply the algorithm step by step:
1.Initialize an empty stack to hold operators.
2.Scan the infix expression from left to right:
3.
1. A: Append to postfix.
2. +: Push onto the stack.
3. B: Append to postfix.
4. ): Pop ‘+’ from the stack and append to postfix.
5. *: Push ‘*’ onto the stack.
6. C: Append to postfix.
7. -: Pop ‘*’ from the stack and append to postfix.
8. D: Append to postfix.
9. /: Push ‘/’ onto the stack.
10.E: Append to postfix.
• The resulting postfix expression is: AB+C*-DE/.
• So, the converted postfix
23-03-2024 M SUNITHA 33
35. EXAMPLE PROBLEMS:
• K + L - MN + (O^P) * W/U/V * T + Q -> KL+MN-
OP^WU/V/T+Q+
• 2 ^ 5 * (3 - 4) -> 2 5 ^ 3 4 - *
• mn+ (p-q)+r -> mnpq-+r+
• X - Y / (Z + U) * V -> XY ZU+/V*-
• x^y/ (5z)+2 -> xy^5z/2+
23-03-2024 M SUNITHA 35
36. Postfix Evaluation:
1.Create an empty stack to store operands (or values).
2.Scan the given postfix expression from left to right and
perform the following for each element:
1.If the element is a number, push it onto the stack.
2.If the element is an operator, pop the top two operands from the stack,
apply the operator, and push the result back onto the stack.
3.Repeat steps 2 until you’ve processed all elements in the
expression.
4.The final result will be the top element in the stack.
23-03-2024 M SUNITHA 36
38. Recursion and the Call Stack
1.Recursion and the Call Stack:
1.A recursive function is one that calls itself during its execution.
2.When a function calls itself, the system uses a call stack to keep track
of the function calls.
3.Each function call creates a stack frame that stores local variables
and the return address.
4.The stack frame is popped off the stack when the function returns.
23-03-2024 M SUNITHA 38
39. Example:
1.Factorial Function Example:
1.Let’s consider calculating the factorial of an integer as an example.
2.The factorial of a positive integer n (denoted as n!) is the product of all
positive integers from 1 to n.
3.To find n!, we multiply n by the factorial of the number that is one less
than n.
4.For example, 5! = 5 × 4!, where 4! = 4 × 3!, and so on.
2.Explanation:
1.The base case is when n = 1, where the result is 1 because 1! = 1.
2.The recursive case calls the function with a smaller value of n: factorial(n)
= n × factorial(n – 1).
3.The function keeps calling itself until it reaches the base case.
4.The stack keeps track of the function calls and their local variables.
•
23-03-2024 M SUNITHA 39
43. Queue:
• A queue is a linear data structure where elements are
stored in the FIFO (First In First Out) principle where the
first element inserted would be the first element to be
accessed.
• A Queue Data Structure is a fundamental concept in computer science used for
storing and managing data in a specific order. It follows the principle of “First in,
First out” (FIFO), where the first element added to the queue is the first one to be
removed. Queues are commonly used in various algorithms and applications for
their simplicity and efficiency in managing data flow.
23-03-2024 M SUNITHA 43
45. Here are the basic operations associated with a
queue in C:
1.Enqueue: Adds an element to the end of the queue.
2.Dequeue: Removes an element from the beginning of the
queue.
3.isEmpty(): Checks if the queue is empty.
4.isFull(): Checks whether the queue is full.
5.Peek(): Retrieves the first element from the queue without
removing it.
23-03-2024 M SUNITHA 45
46. Queue Operations:
1.Enqueue (Insertion):
1.Enqueue operation adds an element to the end of the queue.
2.It’s like someone joining the back of a line.
3.In code, it’s implemented by adding an element to the rear of the queue.
2.Dequeue (Removal):
1.Dequeue operation removes an element from the front of the queue.
2.It’s akin to the person at the front of the line being served and leaving.
3.In code, it involves removing the front element.
23-03-2024 M SUNITHA 46
47. Queue Operations:
1.Peek (Front):
1.Peek operation retrieves the first element from the queue without
removing it.
2.It’s like checking who’s at the front of the line.
3.In code, it returns the front element.
2.isFull():
1.Checks if the queue is full (reached its maximum capacity).
2.Useful when implementing a bounded queue (with a fixed size).
3.isEmpty():
1.Checks if the queue is empty (contains no elements).
2.Useful to prevent dequeuing from an empty queue.
23-03-2024 M SUNITHA 47
48. Array Implementation
1.Array Implementation:
1.Enqueue (Insertion):
1.Adding an element to the end of the queue (rear).
2.Time Complexity: O(1) (constant time).
3.Explanation: We simply increment the rear pointer and put the value in the array.
2.Dequeue (Removal):
1.Removing an element from the beginning of the queue.
2.Time Complexity: O(1) (constant time).
3.Explanation: We change the front pointer to the next element.
3.Peek (Front):
1.Retrieving the first element without removing it.
2.Time Complexity: O(1) (constant time).
23-03-2024 M SUNITHA 48
53. Application of Queues:
• Some common applications of Queue data structure :
1. Task Scheduling: Queues can be used to schedule tasks based on priority or the order in which they were received.
2. Resource Allocation: Queues can be used to manage and allocate resources, such as printers or CPU processing time.
3. Batch Processing: Queues can be used to handle batch processing jobs, such as data analysis or image rendering.
4. Message Buffering: Queues can be used to buffer messages in communication systems, such as message queues in
messaging systems or buffers in computer networks.
5. Event Handling: Queues can be used to handle events in event-driven systems, such as GUI applications or simulation
systems.
6. Traffic Management: Queues can be used to manage traffic flow in transportation systems, such as airport control
systems or road networks.
7. Operating systems: Operating systems often use queues to manage processes and resources. For example, a process
scheduler might use a queue to manage the order in which processes are executed.
8. Network protocols: Network protocols like TCP and UDP use queues to manage packets that are transmitted over the
network. Queues can help to ensure that packets are delivered in the correct order and at the appropriate rate.
9. Printer queues :In printing systems, queues are used to manage the order in which print jobs are processed. Jobs are
added to the queue as they are submitted, and the printer processes them in the order they were received.
10.Web servers: Web servers use queues to manage incoming requests from clients. Requests are added to the queue as
they are received, and they are processed by the server in the order they were received.
11.Breadth-first search algorithm: The breadth-first search algorithm uses a queue to explore nodes in a graph level-by-
level. The algorithm starts at a given node, adds its neighbors to the queue, and then processes each neighbor in turn.
23-03-2024 M SUNITHA 53
55. Dequeue Algorithm
• Dequeue Algorithm:
• Step 1: Check if the queue is empty or not by comparing the number of
elements in the queue with 0.
• Step 2: If the queue is empty, then display an underflow message and end the
program.
• Step 3: If the queue is not empty, then remove the element at the front of the
queue and increment the front pointer.
•
23-03-2024 M SUNITHA 55
58. Circular Queue
• Why was the concept of the circular queue introduced?
• There was one limitation in the array implementation of Queue. If
the rear reaches to the end position of the Queue then there might
be possibility that some vacant spaces are left in the beginning
which cannot be utilized. So, to overcome such limitations, the
concept of the circular queue was introduced.
• What is a Circular Queue?
• A circular queue is similar to a linear queue as it is also based on
the FIFO (First In First Out) principle except that the last position is
connected to the first position in a circular queue that forms a circle.
It is also known as a Ring Buffer.
23-03-2024 M SUNITHA 58
61. • Operations on Circular Queue
• Front: It is used to get the front element from the Queue.
• Rear: It is used to get the rear element from the Queue.
• enQueue(value): This function is used to insert the new value
in the Queue. The new element is always inserted from the rear
end.
• deQueue(): This function deletes an element from the Queue.
The deletion in a Queue always takes place from the front end.
23-03-2024 M SUNITHA 61
62. Operations on Circular Queue:
• Front: Get the front item from the queue.
• Rear: Get the last item from the queue.
• enQueue(value) This function is used to insert an element into the
circular queue. In a circular queue, the new element is always inserted
at the rear position.
• Check whether the queue is full – [i.e., the rear end is in just before the front
end in a circular manner].
• If it is full then display Queue is full.
• If the queue is not full then, insert an element at the end of the queue.
• deQueue() This function is used to delete an element from the
circular queue. In a circular queue, the element is always deleted from
the front position.
• Check whether the queue is Empty.
• If it is empty then display Queue is empty.
• If the queue is not empty, then get the last element and remove it from the queue.
23-03-2024 M SUNITHA 62
63. • Enqueue operation
• The steps of enqueue operation are given below:
• First, we will check whether the Queue is full or not.
• Initially the front and rear are set to -1. When we insert the first
element in a Queue, front and rear both are set to 0.
• When we insert a new element, the rear gets incremented,
i.e., rear=rear+1.
• Scenarios for inserting an element
• There are two scenarios in which queue is not full:
• If rear != max - 1, then rear will be incremented
to mod(maxsize) and the new value will be inserted at the rear end
of the queue.
• If front != 0 and rear = max - 1, it means that queue is not full,
then set the value of rear to 0 and insert the new element there.
23-03-2024 M SUNITHA 63
64. Algorithm to insert an element in a circular
queue
• Step 1: IF (REAR+1)%MAX = FRONT
• Write " OVERFLOW "
• Goto step 4
• [End OF IF]
• Step 2: IF FRONT = -1 and REAR = -1
• SET FRONT = REAR = 0
• ELSE IF REAR = MAX - 1 and FRONT ! = 0
• SET REAR = 0
• ELSE
• SET REAR = (REAR + 1) % MAX
• [END OF IF]
• Step 3: SET QUEUE[REAR] = VAL
• Step 4: EXIT
23-03-2024 M SUNITHA 64
65. Dequeue Operation
• The steps of dequeue operation are given below:
• First, we check whether the Queue is empty or not. If the queue
is empty, we cannot perform the dequeue operation.
• When the element is deleted, the value of front gets
decremented by 1.
• If there is only one element left which is to be deleted, then the
front and rear are reset to -1.
23-03-2024 M SUNITHA 65
66. Algorithm to delete an element from the circular queue
• Step 1: IF FRONT = -1
• Write " UNDERFLOW "
• Goto Step 4
• [END of IF]
• Step 2: SET VAL = QUEUE[FRONT]
• Step 3: IF FRONT = REAR
• SET FRONT = REAR = -1
• ELSE
• IF FRONT = MAX -1
• SET FRONT = 0
• ELSE
• SET FRONT = FRONT + 1
• [END of IF]
• [END OF IF]
Step 4: EXIT
23-03-2024 M SUNITHA 66
71. TIME COMPLEXITY VALUES FOR
QUEUE AND CIRCULAR QUEUE:
• QUEUE:
• Enqueue: O(1) for both array-based and linked list-based queues.
• Dequeue: O(n) for array-based queues, but still O(1) for linked list-based
queues.
• CIRCULAR QUEUE:
• Enqueue: O(1) for both array-based and linked list-based circular queues.
• Dequeue: O(1) for both array-based and linked list-based circular queues.
SPACE COMPLEXITY IS SAME FOR QUEUE AND CIRCULAR QUEUE
• Enqueue: O(1).
• Dequeue: O(n)
23-03-2024 M SUNITHA 71
72. The circular Queue can be used in the
following scenarios:
• The circular Queue can be used in the following scenarios:
• Memory management: The circular queue provides memory
management. As we have already seen that in linear queue, the
memory is not managed very efficiently. But in case of a circular
queue, the memory is managed efficiently by placing the elements in
a location which is unused.
• CPU Scheduling: The operating system also uses the circular
queue to insert the processes and then execute them.
• Traffic system: In a computer-control traffic system, traffic light is
one of the best examples of the circular queue. Each light of traffic
light gets ON one by one after every jinterval of time. Like red light
gets ON for one minute then yellow light for one minute and then
green light. After green light, the red light gets ON.
23-03-2024 M SUNITHA 72