0% found this document useful (0 votes)
4 views

DSA_Module 2

Uploaded by

shubhangpatil14
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

DSA_Module 2

Uploaded by

shubhangpatil14
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Module 2

Dynamic Memory Allocation


Since C is a structured language, it has some fixed rules for programming. One of them
includes changing the size of an array. An array is a collection of items stored at
contiguous memory locations.

As can be seen, the length (size) of the array above is 9. But what if there is a
requirement to change this length (size)? For example,
 If there is a situation where only 5 elements are needed to be entered in this array.
In this case, the remaining 4 indices are just wasting memory in this array. So there
is a requirement to lessen the length (size) of the array from 9 to 5.
 Take another situation. In this, there is an array of 9 elements with all 9 indices filled.
But there is a need to enter 3 more elements in this array. In this case, 3 indices more
are required. So the length (size) of the array needs to be changed from 9 to 12.

This procedure is referred to as Dynamic Memory Allocation in C.


Therefore, C Dynamic Memory Allocation can be defined as a procedure in which the
size of a data structure (like Array) is changed during the runtime.
C provides some functions to achieve these tasks. There are 4 library functions provided
by C defined under <stdlib.h> header file to facilitate dynamic memory allocation in C
programming. They are:
1. malloc()
2. calloc()
3. free()
4. realloc()
Let’s look at each of them in greater detail.

C malloc() method
The “malloc” or “memory allocation” method in C is used to dynamically allocate a
single large block of memory with the specified size. It returns a pointer of type void
which can be cast into a pointer of any form. It doesn’t Initialize memory at execution
time so that it has initialized each block with the default garbage value initially.
Syntax of malloc() in C
ptr = (cast-type*) malloc(byte-size);
For Example:

ptr = (int*) malloc(100 * sizeof(int));


Since the size of int is 4 bytes, this statement will allocate 400 bytes of memory. And, the
pointer ptr holds the address of the first byte in the allocated memory.
Notes By- Prof. Ankita Mandore, CSE (Data Science), DSCE.
If space is insufficient, allocation fails and returns a NULL pointer.

C calloc() method
1. “calloc” or “contiguous allocation” method in C is used to dynamically allocate the
specified number of blocks of memory of the specified type. it is very much similar
to malloc() but has two different points and these are:
2. It initializes each block with a default value ‘0’.
3. It has two parameters or arguments as compare to malloc().
Syntax of calloc() in C
ptr = (cast-type*)calloc(n, element-size);
here, n is the no. of elements and element-size is the size of each element.

For Example:
ptr = (float*) calloc(25, sizeof(float));
This statement allocates contiguous space in memory for 25 elements each with the size
of the float.

If space is insufficient, allocation fails and returns a NULL pointer.

C free() method
“free” method in C is used to dynamically de-allocate the memory. The memory
allocated using functions malloc() and calloc() is not de-allocated on their own. Hence
the free() method is used, whenever the dynamic memory allocation takes place. It
helps to reduce wastage of memory by freeing it.
Notes By- Prof. Ankita Mandore, CSE (Data Science), DSCE.
Syntax of free() in C
free(ptr);

C realloc() method
“realloc” or “re-allocation” method in C is used to dynamically change the memory
allocation of a previously allocated memory. In other words, if the memory previously
allocated with the help of malloc or calloc is insufficient, realloc can be used
to dynamically re-allocate memory. re-allocation of memory maintains the already
present value and new blocks will be initialized with the default garbage value.
Syntax of realloc() in C
ptr = realloc(ptr, newSize);
where ptr is reallocated with new size 'newSize'.

If space is insufficient, allocation fails and returns a NULL pointer.


Notes By- Prof. Ankita Mandore, CSE (Data Science), DSCE.
Queues

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.

A queue can be defined as an ordered list which enables insert operations to be performed at one
end called REAR and delete operations to be performed at another end called FRONT.

Basic Operations of Queue Data Structure


 Enqueue (Insert): Adds an element to the rear of the queue.
 Dequeue (Delete): Removes and returns the element from the front of the queue.
 Peek: Returns the element at the front of the queue without removing it.
 Empty: Checks if the queue is empty.
 Full: Checks if the queue is full.
Applications of Queue
 Task scheduling in operating systems
 Data transfer in network communication
 Simulation of real-world systems (e.g., waiting lines)
 Priority queues for event processing queues for event processing

Notes By- Prof. Ankita Mandore, CSE (Data Science), DSCE.


Key Differences between Stack and Queue

Feature Stack Queue

A linear data structure that follows A linear data structure that follows
Definition the Last In First Out the First In First Out
(LIFO) principle. (FIFO) principle.

Enqueue (add an item), Dequeue


Primary Push (add an item), Pop (remove an
(remove an item), Front (view the first
Operations item), Peek (view the top item)
item), Rear (view the last item)

Elements are added and removed from Elements are added at the rear and
Insertion/Removal
the same end (the top). removed from the front.

Function call management (call stack), Scheduling processes in operating


expression evaluation and syntax systems, managing requests in a
Use Cases
parsing, undo mechanisms in text printer queue, breadth-first search in
editors. graphs.

Browser history (back button), Customer service lines, CPU task


Examples
reversing a word. scheduling.

Real-World A stack of plates: you add and remove A queue at a ticket counter: the first
Analogy plates from the top. person in line is the first to be served.

Typically uses a contiguous block of Typically uses a circular buffer or


Memory Structure
memory or linked list. linked list.

Notes By- Prof. Ankita Mandore, CSE (Data Science), DSCE.


Types of Queue

Simple Queue or Linear Queue


In Linear Queue, an insertion takes place from one end while the deletion occurs from another
end. The end at which the insertion takes place is known as the rear end, and the end at which the
deletion takes place is known as front end. It strictly follows the FIFO rule.
The major drawback of using a linear Queue is that insertion is done only from the rear end. If
the first three elements are deleted from the Queue, we cannot insert more elements even though
the space is available in a Linear Queue. In this case, the linear Queue shows the overflow
condition as the rear is pointing to the last element of the Queue.
Real-life examples of queues are a ticket queue outside a ticket counter, students standing in a
queue for assembly prayer on the school grounds, and a queue of persons standing outside the
booking counter of a theatre. In all these examples, the person standing first in the line is the first
one for access.

Notes By- Prof. Ankita Mandore, CSE (Data Science), DSCE.


Algorithm to insert an item into a simple queue
SQEnqueue (Q[], FRONT, REAR, MAX, ITEM)
1. [Queue is already filled?]
a. IF REAR = MAX-1 THEN
Print Overflow & return
2. [Find the new value of rear]
a. IF REAR=-1 THEN [Q is empty initially]
Set FRONT: =0 and REAR: =0
ELSE
Set REAR: =REAR+1
[End of IF]
3. Set Q [REAR]:=ITEM
4. Return

Algorithm to delete an item into a simple queue


SQDequeue (Q [], FRONT, REAR, MAX, ITEM)
1. [Queue is already empty?]
a. IF FRONT = -1 THEN
Print Underflow & return
2. Set ITEM: = Q [FRONT]
3. [Find the new value of front]
a. IF FRONT=REAR THEN [Single element in Q]
Set FRONT: =-1 and REAR: =-1
ELSE
Set FRONT: = FRONT +1
[End of IF]
4. Return

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.

Notes By- Prof. Ankita Mandore, CSE (Data Science), DSCE.


Applications of Circular Queue
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
interval 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

Scenarios for inserting an element


There are two scenarios in which queue is not full:

o 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.
o 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.

Notes By- Prof. Ankita Mandore, CSE (Data Science), DSCE.


There are two cases in which the element cannot be inserted:
o When front ==0 && rear = max-1, which means that front is at the first position of the
Queue and rear is at the last position of the Queue.
o front== rear + 1;

Algorithm to insert an item into a Circular queue


CQEnqueue (CQ [], FRONT, REAR, MAX, ITEM)
1. [Queue is already filled?]
a. IF (REAR+1) %MAX = FRONT THEN
Print Overflow & return
2. [Find the new value of rear]
a. IF FRONT = -1 and REAR = -1 THEN [Q is empty initially]
Set FRONT: =0 and REAR: =0
ELSE IF REAR = MAX - 1 and FRONT! = 0
Set REAR: = 0
ELSE
Set REAR: = (REAR + 1) % MAX
[End of IF]
3. Set CQ [REAR]:=ITEM
4. Return

Algorithm to delete an item into a Circular queue


CQDequeue (CQ [], FRONT, REAR, MAX, ITEM)
1. [Queue is already empty?]
a. IF FRONT = -1 THEN
Print Underflow & return
2. Set ITEM: = Q [FRONT]
3. [Find the new value of front]
a. IF FRONT=REAR THEN [Single element in Q]
Set FRONT: =-1 and REAR: =-1
ELSE IF FRONT = MAX -1 THEN
Set FRONT: = 0
ELSE
Set FRONT = FRONT + 1
[END of IF]
[END OF IF]
4. Return
Notes By- Prof. Ankita Mandore, CSE (Data Science), DSCE.
Priority Queue
A priority queue is a type of queue that arranges elements based on their priority values.
Elements with higher priority values are typically retrieved or removed before elements with
lower priority values. Each element has a priority value associated with it. When we add an item,
it is inserted in a position based on its priority value.
There are several ways to implement a priority queue, including using an array, linked list, heap,
or binary search tree, binary heap being the most common method to implement. The reason for
using Binary Heap is simple, in binary heaps, we have easy access to the min (in min heap) or
max (in max heap) and binary heap being a complete binary tree are easily implemented using
arrays.

Types of Priority Queue:

1) Ascending Order Priority Queue


As the name suggests, in ascending order priority queue, the element with a lower priority value
is given a higher priority in the priority list. For example, if we have the following elements in a
priority queue arranged in ascending order like 4,6,8,9,10. Here, 4 is the smallest number,
therefore, it will get the highest priority in a priority queue and so when we dequeue from this
type of priority queue, 4 will remove from the queue and dequeue returns 4.
2) Descending order Priority Queue
The root node is the maximum element in a max heap, as you may know. It will also remove the
element with the highest priority first. As a result, the root node is removed from the queue. This
deletion leaves an empty space, which will be filled with fresh insertions in the future. The heap
invariant is then maintained by comparing the newly inserted element to all other entries in the
queue.

Notes By- Prof. Ankita Mandore, CSE (Data Science), DSCE.


Deque (or double-ended queue)
The deque stands for Double Ended Queue. Deque is a linear data structure where the insertion
and deletion operations are performed from both ends. We can say that deque is a generalized
version of the queue.
Though the insertion and deletion in a deque can be performed on both ends, it does not follow
the FIFO rule. The representation of a deque is given as follows -

Types of deque
There are two types of deque -
1. Input restricted queue
2. Output restricted queue

Input restricted Queue


In input restricted queue, insertion operation can be performed at only one end, while deletion
can be performed from both ends.

Output restricted Queue


In output restricted queue, deletion operation can be performed at only one end, while insertion
can be performed from both ends.

Notes By- Prof. Ankita Mandore, CSE (Data Science), DSCE.


Operations performed on deque
There are the following operations that can be applied on a deque -
1. Insertion at front
2. Insertion at rear
3. Deletion at front
4. Deletion at rear

Linked Lists
A linked list, or one-way list, is a linear collection of data elements, called nodes, where the
linear order is given by means of pointers. That is, each node is divided into two parts:
The first part contains the information of the element, and
The second part, called the link field or nextpointer field, contains the address of the
next node in the list
The last node of the list contains pointer to the null.

A pointer variable called START or FIRST which contains the address of the first node. A
special case is the list that has no nodes, such a list is called the null list or empty list and is
denoted by the null pointer in the variable START.

Notes By- Prof. Ankita Mandore, CSE (Data Science), DSCE.


REPRESENTATION OF LINKED LISTS IN MEMORY
Let LIST be a linked list. Then LIST will be maintained in memory as follows.
1. LIST requires two linear arrays such as INFO and LINK-such that INFO[K] and LINK[K]
contains the information part and the nextpointer field of a node of LIST.
2. LIST also requires a variable name such as START which contains the location of the
beginning of the list, and a nextpointer sentinel denoted by NULL-which indicates the
end of the list.
3. The subscripts of the arrays INFO and LINK will be positive, so choose NULL = 0, unless
otherwise stated.
The following examples of linked lists indicate that the nodes of a list need not occupy adjacent
elements in the arrays INFO and LINK, and that more than one list may be maintained in the
same linear arrays INFO and LINK. However, each list must have its own pointer variable giving
the location of its first node.

Notes By- Prof. Ankita Mandore, CSE (Data Science), DSCE.


REPRESENTING CHAIN IN C
The following capabilities are needed to make linked representation
1. A mechanism for defining a node’s structure, that is, the field it contains. So self-referential
structures can be used
2. A way to create new nodes, so MALLOC functions can do this operation
3. A way to remove nodes that no longer needed. The FREE function handles this operation.

Linked Lists vs Arrays


Here’s the comparison of Linked List vs Arrays
Linked List:
1. Data Structure: Non-contiguous
2. Memory Allocation: Typically allocated one by one to individual elements
3. Insertion/Deletion: Efficient
4. Access: Sequential
Array:
1. Data Structure: Contiguous
2. Memory Allocation: Typically allocated to the whole array
3. Insertion/Deletion: Inefficient
4. Access: Random

Types of Linked List


1. Singly Linked List
2. Doubly Linked List
3. Circular Linked List
4. Circular Doubly Linked List

1. Singly Linked List


Singly linked list is the simplest type of linked list in which every node contains some data and a
pointer to the next node of the same data type.
The node contains a pointer to the next node means that the node stores the address of the next
node in the sequence. A single linked list allows the traversal of data only in one way. Below is
the image for the same:

Notes By- Prof. Ankita Mandore, CSE (Data Science), DSCE.


2. Doubly Linked List
A doubly linked list is a data structure that consists of a set of nodes, each of which contains a
value and two pointers, one pointing to the previous node in the list and one pointing to the next
node in the list. This allows for efficient traversal of the list in both directions, making it suitable
for applications where frequent insertions and deletions are required.

Representation of Doubly Linked List in Data Structure


In a data structure, a doubly linked list is represented using nodes that have three fields:
1. Data
2. A pointer to the next node (next)
3. A pointer to the previous node (prev)

Notes By- Prof. Ankita Mandore, CSE (Data Science), DSCE.


3. Circular Linked List

A circular linked list is a special type of linked list where all the nodes are connected to form a
circle. Unlike a regular linked list, which ends with a node pointing to NULL, the last node in a
circular linked list points back to the first node. This means that you can keep traversing the list
without ever reaching a NULL value.

Types of Circular Linked Lists


We can create a circular linked list from both singly linked lists and doubly linked lists. So,
circular linked list is basically of two types:

1. Circular Singly Linked List


In Circular Singly Linked List, each node has just one pointer called the “next” pointer. The next
pointer of last node points back to the first node and this results in forming a circle. In this type
of Linked list, we can only move through the list in one direction.

2. Circular Doubly Linked List:


In circular doubly linked list, each node has two pointers prev and next, similar to doubly linked
list. The prev pointer points to the previous node and the next points to the next node. Here, in
addition to the last node storing the address of the first node, the first node will also store the
address of the last node.

Notes By- Prof. Ankita Mandore, CSE (Data Science), DSCE.

You might also like