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

Dec 2023 Data Structure Solution Mumbai University

Mumbai University Data Structure Solution Dec 2023 Computer Engineering

Uploaded by

Kranti Gajmal
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)
499 views

Dec 2023 Data Structure Solution Mumbai University

Mumbai University Data Structure Solution Dec 2023 Computer Engineering

Uploaded by

Kranti Gajmal
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/ 20

Data Structure (Sem-III) Model Answer Paper Dec 2023

Q1)

A) Define ADT with an example.


 Abstract Data type (ADT) - is a type for objects whose behavior is defined by a set of value and
a set of operations. The definition of ADT only mentions what operations are to be performed
but not how these operations will be implemented.
 It does not specify how data will be organized in memory and what algorithms will be used
for implementing the operations.
 It is called “abstract” as it gives an implementation-independent view. The process of
providing only the essentials and hiding the details is known as abstraction.


For eg. Stack ADT

1 In Stack ADT implementation instead of data being stored in each node, the pointer to data is stored.

2 The program allocates memory for the data and address is passed to the stack ADT.

3 The head node and the data nodes are encapsulated in the ADT. The calling function can only see the
pointer to the stack.

4 The stack head structure also contains a pointer to top and count of number of entries currently in stack. As
Push(), pop(),peek(),size(), isempty(), isfull() is already implemented in STACK ADT, only programmer has to
use this function for implementing program on stack
B) Evaluate the postfix expression 94*28+- using stack ADT Show the process stepwise.
 Initialize an empty stack.
 Scan the postfix expression from left to right.
 For each character in the expression:
If the character is an operand (number), push it onto the stack.
If the character is an operator, pop the required number of operands from the stack, perform the
operation, and push the result back onto the stack.

So final answer is 26 which is removed finally from stack as answer.

C) Justify the statement with suitable example: "Circular queue overcomes the disadvantage of linear
queue".
A circular queue is the extended version of a regular queue where the last element is connected to the
first element. Thus forming a circle- like structure.
The circular queue solves the major limitation of the normal queue. In a normal queue, after a bit of
insertion and deletion, there will be non- usable empty space.

Here, indexes 0 and 1 can only be used after resetting the queue (deletion of all elements). This
reduces the actual size of the queue.

How Circular Queue Works


Circular Queue works by the process of circular increment i.e. when we try to increment the pointer
and we reach the end of the queue, we start from the beginning of the queue. Here, the circular
increment is performed by modulo division with the queue size. That is,

If REAR + 1 == 5 (overflow!), REAR = (REAR + 1) %5 = 0 (start of queue)

D) Differentiate between linear search and binary search.

Q.2

A) Construct Huffman tree and determine the code for each symbol in the string BCAADDDCCACACAC
1. Calculate the frequency of each character in the string. Frequency of string

2. Sort the characters in increasing order of the frequency. These are stored in a priority queue Q.

Characters sorted according to the frequency

3. Make each unique character as a leaf node.

4. Create an empty node z. Assign the minimum frequency to the left child of z and assign the second minimum

frequency to the right child of z. Set the value of the z as the sum of the above two minimum frequencies.

Getting the sum of the least numbers


5. Remove these two minimum frequencies from Q and add the sum into the list of frequencies (* denote the

internal nodes in the figure above).


6. Insert node z into the tree.
7. Repeat steps 3 to 5 for all the characters. Repeat steps 3 to 5 for all the

characters. Repeat steps 3 to 5 for all the characters.

8. For each non-leaf node, assign 0 to the left edge and 1 to the right edge.

9. Assign 0 to the left edge and 1 to the right edge

For sending the above string over a network, we have to send the tree as well as the above compressed-code.

The total size is given by the table below.

Character Frequency Code Size

A 5 11 5*2 = 10

B 1 100 1*3 = 3
C 6 0 6*1 = 6

D 3 101 3*3 = 9

4 * 8 = 32 bits 15 bits 28 bits

Without encoding, the total size of the string was 120 bits. After encoding the size is reduced to

32 + 15 + 28 =75.

B) Discuss the cases of deleting a node from Binary Search Tree with suitable example.

Binary search tree (BST)

 A Binary Search Tree (BST) is a special type of tree where the value of the left child node’s always
less than the parent node and the value of the right child node is greater than the parent node.
 Commonly performed operations on binary search trees are searching, insertion, and deletion.
 Here, we see Delete operation in detail.

Delete Operation

 In a binary search tree, the Delete function is used to delete the specified node.
 But, delete a node from a binary search tree in such a way, that the property of the binary search tree
doesn't violate.
 To achieve this there are three methods for deleting a node from a binary search tree are used.

Method - 1: Deletion of A Node Having No Child (Leaf Node)


Method - 2: Deletion of A Node Having Only One Child Node
Method - 3: Deletion of A Node Having Two Children Nodes

Method - 1: Deletion of A Node Having No Child (Leaf Node)

 It is the simplest method when deleting a node is the leaf node.


 In this, the leaf node with is replaced the NULL and simply free the allocated space.
 Consider the following example where leaf node with value = 30 is deleted from the BST:
Method - 2: Deletion of A Node Having Only One Child Node

 In this, replace the node that is going to be deleted with its only child node and then delete the child
node, which now contains the value which is to be deleted.
 Replace it with the NULL and free the allocated space.
 Consider the following example where the node with one child node whose value = 25 is deleted from
the BST:

Method - 3: Deletion of A Node Having Two Children Nodes

 It is a quite complex method case compared to the other two methods.


 In this, the node which is to be deleted is replaced with its in-order successor or predecessor recursively
until the node to be deleted is replaced on the leaf of the tree.
 After this, replace the node with NULL and free the allocated space. Consider the following example
where the node with two child nodes whose value = 60 is deleted from the BST:

In-order Traversal Sequence of the following Tree is 15, 25, 30, 60, 65, 75, 85, 90, 95.
A node with two children can be deleted from the BST in the following two ways:
Way 1:

 Visit the right sub-tree of the deleting node.


 Take the least value node called the in-order successor node.
 Replace the deleting node with its in-order successor node.
 In this way take the node with value 65 which is the least valued in-order successor node of node 60
that is to be deleted.

Way 2:

 Visit the left sub-tree of the deleting node.


 Take the greatest value node called the in-order predecessor node.
 Replace the deleting node with its in-order predecessor node.
 In this way take the node with value 30 which is the greatest valued in-order predecessor node of the
node 60 that is to be deleted.

Q.3

A) Write a program in C to implement queue ADT using linked list.


#include <stdio.h>
#include <stdlib.h>

struct node
{
int info;
struct node *ptr;
}*front,*rear,*temp,*front1;
int frontelement();
void enq(int data);
void deq();
void empty();
void display();
void create();
void queuesize();

int count = 0;

void main()
{
int no, ch, e;

printf("\n 1 - Enque");
printf("\n 2 - Deque");
printf("\n 3 - Front element");
printf("\n 4 - Empty");
printf("\n 5 - Exit");
printf("\n 6 - Display");
printf("\n 7 - Queue size");
create();
while (1)
{
printf("\n Enter choice : ");
scanf("%d", &ch);
switch (ch)
{
case 1:
printf("Enter data : ");
scanf("%d", &no);
enq(no);
break;
case 2:
deq();
break;
case 3:
e = frontelement();
if (e != 0)
printf("Front element : %d", e);
else
printf("\n No front element in Queue as queue is empty");
break;
case 4:
empty();
break;
case 5:
exit(0);
case 6:
display();
break;
case 7:
queuesize();
break;
default:
printf("Wrong choice, Please enter correct choice ");
break;
}
}
}

/* Create an empty queue */


void create()
{
front = rear = NULL;
}

/* Returns queue size */


void queuesize()
{
printf("\n Queue size : %d", count);
}

/* Enqueing the queue */


void enq(int data)
{
if (rear == NULL)
{
rear = (struct node *)malloc(1*sizeof(struct node));
rear->ptr = NULL;
rear->info = data;
front = rear;
}
else
{
temp=(struct node *)malloc(1*sizeof(struct node));
rear->ptr = temp;
temp->info = data;
temp->ptr = NULL;

rear = temp;
}
count++;
}

/* Displaying the queue elements */


void display()
{
front1 = front;

if ((front1 == NULL) && (rear == NULL))


{
printf("Queue is empty");
return;
}
while (front1 != rear)
{
printf("%d ", front1->info);
front1 = front1->ptr;
}
if (front1 == rear)
printf("%d", front1->info);
}

/* Dequeing the queue */


void deq()
{
front1 = front;

if (front1 == NULL)
{
printf("\n Error: Trying to display elements from empty queue");
return;
}
else
if (front1->ptr != NULL)
{
front1 = front1->ptr;
printf("\n Dequed value : %d", front->info);
free(front);
front = front1;
}
else
{
printf("\n Dequed value : %d", front->info);
free(front);
front = NULL;
rear = NULL;
}
count--;
}
/* Returns the front element of queue */
int frontelement()
{
if ((front != NULL) && (rear != NULL))
return(front->info);
else
return 0;
}

/* Display if queue is empty or not */


void empty()
{
if ((front == NULL) && (rear == NULL))
printf("\n Queue empty");
else
printf("Queue not empty");
}

B) Construct an AVL tree by inserting the following elements in the given order Apply necessary
rotations wherever required. 54, 12, 24, 68, 85, 99, 42, 27, 87, 80

LR-Left Rotation
Right Rotation
Q.4

BFS Program 5 Marks


#include <stdio.h>

int n, i, j, visited[10], queue[10], front = -1, rear = -1;


int adj[10][10];

void bfs(int v)
{
for (i = 1; i <= n; i++)
if (adj[v][i] && !visited[i])
queue[++rear] = i;
if (front <= rear)
{
visited[queue[front]] = 1;
bfs(queue[front++]);
}
}

void main()
{
int v;
printf("Enter the number of vertices: ");
scanf("%d", &n);
for (i = 1; i <= n; i++)
{
queue[i] = 0;
visited[i] = 0;
}
printf("Enter graph data in matrix form: \n");
for (i = 1; i <= n; i++)
for (j = 1; j <= n; j++)
scanf("%d", &adj[i][j]);
printf("Enter the starting vertex: ");
scanf("%d", &v);
bfs(v);
printf("The node which are reachable are: \n");
for (i = 1; i <= n; i++)
if (visited[i])
printf("%d\t", i);
else
printf("BFS is not possible. Not all nodes are reachable");
return 0;
}

So Final BFS SEQUENCE of the Graph is

ABDCEGF

Each function carries 2.5 Marks


#include <stdio.h>
#include <stdlib.h>

// Definition of a doubly linked list node


struct Node {
int data;
struct Node* prev;
struct Node* next;
};
Function to Delete a Node after a Given Node

void deleteNodeAfter(struct Node* givenNode) {


if (givenNode == NULL || givenNode->next == NULL) {
return;
}
struct Node* nodeToDelete = givenNode->next;
givenNode->next = nodeToDelete->next;
if (nodeToDelete->next != NULL) {
nodeToDelete->next->prev = givenNode;
}
free(nodeToDelete);
}
Function to Find Node with Smallest Data Value
c
Copy code
struct Node* findSmallestNode(struct Node* head) {
if (head == NULL) {
return NULL;
}
struct Node* smallest = head;
struct Node* current = head->next;
while (current != NULL) {
if (current->data < smallest->data) {
smallest = current;
}
current = current->next;
}
return smallest;
}

Function to Display the List

void displayList(struct Node* head) {


struct Node* current = head;
while (current != NULL) {
printf("%d -> ", current->data);
current = current->next;
}
printf("NULL\n");
}

Function to Insert a Node at the End of the List

void insertAtEnd(struct Node** headRef, int data) {


struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;

if (*headRef == NULL) {
newNode->prev = NULL;
*headRef = newNode;
return;
}

struct Node* last = *headRef;


while (last->next != NULL) {
last = last->next;
}

last->next = newNode;
newNode->prev = last;
}

Q.5

A) Build a Binary Search Tree, given the following sequences:

Inorder: 35, 41, 48, 52, 57, 72, 79, 85, 86, 90

Preorder: 57, 41, 35. 52, 48, 90, 72, 85, 79, 86

B) What is topological sorting? Explain Topological Sorting with an example.

 Topological sorting for Directed Acyclic Graph (DAG) is a linear ordering of vertices such that for
every directed edge uv, vertex u comes before v in the ordering. Topological Sorting for a graph is
not possible if the graph is not a DAG.
 For example, a topological sorting of the following graph is “5 4 2 3 1 0”.

in-Degree: Compute the in-degree (number of incoming edges) for each vertex.
Queue: Initialize a queue with all vertices that have in-degree 0.
the Queue:
 Remove a vertex from the front of the queue.
 Add it to the topological ordering.
 Decrease the in-degree of its neighbors by 1.
 If any neighbor's in-degree becomes 0, add it to the queue

 There can be more than one topological sorting for a graph. For example, another topological
sorting of the following graph is “4 5 2 3 1 0”. The first vertex in topological sorting is always a
vertex with in-degree as 0

C) What is Collision? Using linear probing, insert the following values in the hash table of size 11 & count
the no. of collisions:

Hash collision is when two distinct pieces of data in a hash table share the same hash value. The hash
value in this case is derived from a hash function which takes a data input and returns a fixed length of
bits.

83, 53, 64, 25, 39, 96, 12, 71.

Q6

A) Write short note on Priority Queue


Priority Queue is an extension of queue with following properties.
• Every item has a priority associated with it.
• An element with high priority is de-queued before an element with low if two elements have the
same priority, they are served according to their order in the queue.
• A typical priority queue supports following operations.
a. Insert (item, priority): Inserts an item with given priority.
b. GetHighestPriority (): Returns the highest priority item.
c. DeleteHighestPriority (): Removes the highest priority item.

How is Priority assigned to the elements in a Priority Queue?


In a priority queue, generally, the value of an element is considered for assigning the priority.
For example, the element with the highest value is assigned the highest priority and the element with
the lowest value is assigned the lowest priority. The reverse case can also be used i.e., the element with
the lowest value can be assigned the highest priority. Also, the priority can be assigned according to our
needs.
Operations of a Priority Queue:
A typical priority queue supports the following operations:
1) Insertion in a Priority Queue
When a new element is inserted in a priority queue, it moves to the empty slot from top to bottom and
left to right. However, if the element is not in the correct place then it will be compared with the parent
node. If the element is not in the correct order, the elements are swapped. The swapping process
continues until all the elements are placed in the correct position.
2) Deletion in a Priority Queue
As you know that in a max heap, the maximum element is the root node. And it will remove the element
which has maximum priority first. Thus, you remove the root node from the queue. This removal creates
an empty slot, which will be further filled with new insertion. Then, it compares the newly inserted
element with all the elements inside the queue to maintain the heap invariant.
3) Peek in a Priority Queue
This operation helps to return the maximum element from Max Heap or the minimum element from Min
Heap without deleting the node from the priority queue.
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 DE queue from this type of priority queue, 4 will
remove from the queue and DE queue 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.
B) Write a function in C to count the number of nodes in Singly Linked List.
#include <stdio.h>
#include <stdlib.h>

// Definition of a singly linked list node


struct Node {
int data;
struct Node* next;
};

// Function to count the number of nodes in a singly linked list


int countNodes(struct Node* head) {
int count = 0;
struct Node* current = head;
while (current != NULL) {
count++;
current = current->next;
}
return count;
}

// Helper function to create a new node


struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}

// Helper function to add a node at the end of the list


void appendNode(struct Node** headRef, int data) {
struct Node* newNode = createNode(data);
struct Node* last = *headRef;
if (*headRef == NULL) {
*headRef = newNode;
return;
}
while (last->next != NULL) {
last = last->next;
}
last->next = newNode;
}

// Helper function to print the list (for testing purposes)


void printList(struct Node* head) {
struct Node* current = head;
while (current != NULL) {
printf("%d -> ", current->data);
current = current->next;
}
printf("NULL\n");
}

int main() {
struct Node* head = NULL;
// Creating a sample list: 1 -> 2 -> 3 -> 4 -> NULL
appendNode(&head, 1);
appendNode(&head, 2);
appendNode(&head, 3);
appendNode(&head, 4);

printList(head); // Output the list


int count = countNodes(head);
printf("Number of nodes in the list: %d\n", count); // Output the count
return 0;
}
C) Create a B-tree of order 3 by inserting 87, 94, 59, 98, 63, 7, 27.

Total Marks 10 for stepwise diagrams.

You might also like