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

Data Structure (Imp-Questions)_copy

The document discusses various computer science concepts, including performance measurement of algorithms, balance factors in AVL trees, abstract data types, and types of graphs. It also covers dynamic memory allocation functions, linear data structures, stack operations, and sorting techniques such as selection and insertion sort. Additionally, it explains the characteristics of algorithms and provides examples of data structures and their applications.

Uploaded by

Anuja Borate
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

Data Structure (Imp-Questions)_copy

The document discusses various computer science concepts, including performance measurement of algorithms, balance factors in AVL trees, abstract data types, and types of graphs. It also covers dynamic memory allocation functions, linear data structures, stack operations, and sorting techniques such as selection and insertion sort. Additionally, it explains the characteristics of algorithms and provides examples of data structures and their applications.

Uploaded by

Anuja Borate
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

Q1) Attempt any EIGHT of the following.

[8×2=16]

a) How to measure performance of an algorithm ?


Ans:
1. Time Complexity : Represents the amount of time an algorithm takes to complete as a
function of the size of the input (often expressed using Big O notation).
2. Space Complexity : Represents the amount of memory an algorithm uses as a function of the
size of the input.
3. Empirical Analysis : Running the algorithm with different input sizes and measuring actual
execution time and memory usage.

b) What is the balance factor ? How is it calculated ?


Ans: The balance factor of a node in an AVL (Adelson-Velsky and Landis) tree is the difference
between the heights of its left and right subtrees.
It is calculated as : Balance Factor (BF) = Height of Left Subtree - Height of Right Subtree.

c) What are Abstract Data types ?


Ans: An Abstract Data Type (ADT) is a mathematical model for data types where the behavior is
defined by a set of operations but the implementation is abstracted away. ADTs specify what
operations can be performed, not how they are implemented. Examples of ADTs include : Stack
(LIFO structure), Queue (FIFO structure), List (ordered collection).

d) What is the Ancestor of Node ?


Ans: An ancestor of a node in a tree is any node that lies on the path from the root node to that
specific node, excluding the node itself. For example, in a binary tree, the root node and the
nodes in between it and a specific node are considered ancestors.

e) State the types of graphs.


Ans:
1. Directed Graph : Edges have a direction, represented as ordered pairs (u, v).
2. Undirected Graph : Edges do not have a direction.
3. Cyclic Graph : Contains at least one cycle.
4. Acyclic Graph : No cycles are present.
5. Connected Graph : There is a path between every pair of vertices.
6. Disconnected Graph : Some vertices are not reachable from others.

f) What is space and time complexity ?


Ans:
1. Time Complexity : It measures the amount of time an algorithm takes to complete as a
function of the input size (e.g., O(n), O(log n)).
2. Space Complexity : It measures the amount of memory an algorithm needs as a function of
the input size.
g) Differentiate array and structure.
Ans:
1. Array :
• A collection of elements of the same data type.
• Elements are stored contiguously in memory.
• Fixed size.
• Can be accessed using indices.
2. Structure :
• A collection of variables (elements) of different data types.
• Elements may be stored non-contiguously.
• Size is flexible and can be defined by the number of members.
• Accessed using member names, not indices.

h) What is pointer to pointer ?


Ans: A pointer to pointer is a variable that stores the address of another pointer. It is often used
in dynamic memory allocation, especially when working with arrays of pointers or
multi-dimensional arrays. For example, in C/C++, int **ptr is a pointer to a pointer that can point
to an integer pointer.

i) What is a spanning tree ?


Ans: A spanning tree of a graph is a subgraph that includes all the vertices of the graph, but with
the minimum number of edges (n-1 for n vertices), such that there are no cycles. Every
connected graph has at least one spanning tree.

j) What are data structures ?


Ans: A data structure is a way of organizing and storing data to efficiently perform operations
like insertion, deletion, searching, and sorting. Examples include arrays, linked lists, stacks,
queues, trees, and graphs.

k) What is sorting ? State the techniques of sorting.


Ans: Sorting is the process of arranging elements in a particular order (ascending or
descending). Common sorting techniques include :
• Bubble sort.
• Selection Sort.
• Insertion sort.
• Merge sort.
• Quick sort.

l) What are non-primitive data structures ?


Ans: Non-primitive data structures are data structures that can store multiple values and are
derived from primitive types. They are more complex than primitive data types. Examples
include : Arrays, Linked Lists, Stacks, Queues, Trees, Graphs.
m) What is searching ?
Ans: Searching refers to the process of finding a particular element in a collection (such as an
array, list, or database). Common searching algorithms include :
• Linear Search : Checks each element one by one.
• Binary Search : Divides the collection into two halves and compares the target with the middle
element, reducing the search space by half.

n) Mention the features of ADT.


Ans:
1. Encapsulation : The internal workings of an ADT are hidden from the user.
2. Operations : It defines a set of operations that can be performed on the data.
3. Independence : The implementation of an ADT is independent of its usage.
4. Data abstraction : Focuses on what operations can be performed, not on how they are
implemented.

o) What are the types of linked lists ?


Ans:
1. Singly Linked List : Each node points to the next node.
2. Doubly Linked List : Each node has two pointers, one to the next node and one to the
previous node.
3. Circular Linked List : The last node points to the first node, forming a circle.

p) List down the applications of the list.


Ans:
1. Dynamic Memory Allocation : Lists can store dynamic amounts of data.
2. Implementation of Queues and Stacks : Lists can be used to implement these linear data
structures.
3. Polynomial Representation : A polynomial can be represented as a linked list of its terms.
4. Adjacency List for Graphs : A graph’s adjacency list can be represented using linked lists.

q) What are polynomials ? How is it presented ?


Ans: A polynomial is an algebraic expression involving a sum of powers of a variable multiplied
by coefficients. For example, is a polynomial. It can be represented using :
• Arrays : Each element stores the coefficient of the terms.
• Linked Lists : Each node represents a term with a coefficient and exponent.

r) What are the applications of stacking ?


Ans:
1. Expression Evaluation : Infix, prefix, and postfix expressions are evaluated using stacks.
2. Backtracking Algorithms : Used in algorithms like depth-first search (DFS) in graphs.
3. Undo Mechanism : Used in applications for implementing the undo feature.
4. Function Calls : The call stack is used to manage function calls and recursion.
Q2) Attempt any Four of the following : [4×4=16]

a) Explain different types of Dynamic Memory Allocation functions.


Ans: Dynamic memory allocation in C programming refers to allocating memory at runtime, as
opposed to static memory allocation, which occurs at compile time. In C, the standard library
provides several functions for dynamic memory allocation. These functions allow you to allocate
and free memory dynamically based on the needs of the program.
The main dynamic memory allocation functions are :

1. malloc() (Memory Allocation) :


• Syntax : void* malloc(size_t size);
• Description : Allocates a block of memory of the specified size (in bytes). It returns a pointer to
the first byte of the allocated memory block.
• Use Case : Used when you want to allocate a single block of memory of a specific size but do
not need the memory initialized.
• Return Value : Returns a void* pointer to the allocated memory block, or NULL if the memory
allocation fails.

2. calloc() (Contiguous Allocation) :


• Syntax : void* calloc(size_t num, size_t size);
• Description : Allocates memory for an array of num elements, each of size size bytes. Unlike
malloc(), calloc() initializes all bits of the allocated memory to zero.
• Use Case : Useful when you want to allocate memory for an array or structure and initialize it
to zero.
• Return Value : Returns a void* pointer to the allocated memory, or NULL if the allocation fails.

3. realloc() (Reallocation) :
• Syntax : void* realloc(void* ptr, size_t new_size);
• Description : Changes the size of previously allocated memory blocks. If the ptr is NULL,
realloc() behaves like malloc(). If the new_size is zero, realloc() frees the memory.
• Use Case : Used when you need to resize an already allocated memory block, either to
expand or shrink the allocated space.
• Return Value : Returns a pointer to the reallocated memory, which may be a new memory
address if the block was moved. If allocation fails, NULL is returned, and the original memory
block remains unchanged.

4. free() (Deallocation) :
• Syntax : void free(void* ptr);
• Description : Frees the dynamically allocated memory, releasing it back to the system. After
calling free(), the pointer is no longer valid, and it should not be used.
• Use Case : Used to deallocate memory that was previously allocated by malloc(), calloc(), or
realloc() to avoid memory leaks.
• Return Value : free() does not return any value.
b) Explain Linear Data structure with examples.
Ans:
1. A linear data structure is a type of data structure in which elements are arranged in a
sequential or linear order, where each element is connected to the previous and next element.
In a linear data structure, the elements are stored one after the other, and there is a clear
starting and ending point.
2. In simple terms, linear data structures can be thought of as a collection of elements arranged
in a straight line, where each element has a single predecessor and a single successor (except
the first and last elements).

• Types of Linear Data Structures :

1. Arrays :
• Definition : An array is a collection of elements stored at contiguous memory locations. Each
element can be accessed using its index.
• Example : An array of integers : int numbers[ ] = {10, 20, 30, 40};
Accessing the second element : numbers[1] returns 20.

2. Linked Lists :
• Definition : A linked list consists of nodes, where each node contains data and a reference (or
pointer) to the next node in the sequence.
• Example : Node1 -> Node2 -> Node3
This structure allows for dynamic memory allocation and efficient insertions/deletions.

3. Stacks :
• Definition : A stack is a collection that follows the Last In First Out (LIFO) principle, meaning
the last element added is the first one to be removed.
• Example : Push: 10, 20, 30
Stack: [30] (top), [20], [10]
Pop: Removes 30, stack becomes [20] (top), [10]

4. Queues :
• Definition : A queue is a collection that follows the First In First Out (FIFO) principle, where the
first element added is the first to be removed.
• Example : Enqueue : 10, 20, 30
Queue : [10] (front), [20], [30] (rear)
Dequeue : Removes 10, queue becomes [20] (front), [30] (rear)
c) What is stack ? Explain different operations used in stack.
Ans: A stack is a linear data structure that follows the Last In First Out (LIFO) principle. This
means that the last element added to the stack is the first one to be removed. Stacks are used
in various applications, including function call management, expression evaluation, and
backtracking algorithms.

• Operations on a Stack :

1. Push : This operation adds an element to the top of the stack. If the stack is full (in case of a
fixed-size stack), it may lead to an overflow condition.
2. Pop : This operation removes the top element from the stack and returns it. If the stack is
empty, it may lead to an underflow condition.
3. Peek (or Top) : This operation retrieves the top element of the stack without removing it. This
is useful for checking the value of the top element.
4. isEmpty : This operation checks if the stack is empty. It returns true if there are no elements in
the stack.
5. isFull : This operation checks if the stack is full, applicable in the case of fixed-size stacks. It
returns true if no more elements can be added.

d) What is an algorithm ? Explain its characteristics.


Ans: An algorithm is a well-defined set of instructions or steps designed to perform a specific
task or solve a particular problem. Algorithms are fundamental in computer science, as they
form the basis for computer programs and software applications.

• Characteristics of Algorithms :

1. Finiteness : An algorithm must always terminate after a finite number of steps. It cannot go on
indefinitely.
2. Definiteness : Each step of the algorithm must be precisely defined, with clear and
unambiguous instructions.
3. Input : An algorithm should have clearly defined inputs, which are the data provided before
the algorithm begins.
4. Output : It should produce one or more outputs, which are the results after processing the
inputs.
5. Effectiveness : All operations must be basic enough to be carried out in a finite amount of
time and with available resources.
6. Generality : An algorithm should be general enough to solve all problems of a specific type,
not just a particular instance. It should apply to a wide range of inputs.
e) Explain selection sort technique with example.
Ans: Selection Sort is a simple comparison-based sorting algorithm. It works by repeatedly
finding the minimum (or maximum) element from the unsorted portion of the list and swapping it
with the element at the current position. The algorithm divides the list into two parts: the sorted
part and the unsorted part. Initially, the sorted part is empty, and the unsorted part contains all
the elements. The algorithm progresses by selecting the smallest (or largest) element from the
unsorted part and moving it to the sorted part.

• Steps of Selection Sort Algorithm :


1. Start with the first element in the list.
2. Find the smallest (or largest) element in the unsorted portion of the list.
3. Swap this smallest (or largest) element with the element at the current position.
4. Move to the next element and repeat the process until the entire list is sorted.

• Selection Sort Algorithm (in Detail) :


1. Step 1 (Initial) : The entire list is unsorted.
2. Step 2 : Find the smallest element in the list and swap it with the first element.
3. Step 3 : Move the boundary of the sorted and unsorted parts by one element to the right, and
repeat the process for the remaining unsorted elements.
4. Step 4 : Continue this process until all elements are sorted.

• Example of Selection Sort :


Consider the following unsorted array : [64, 25, 12, 22, 11]
Step-by-Step Process :

1. First Pass :
• The unsorted list is [64, 25, 12, 22, 11].
• Find the minimum element in the entire list: 11.
• Swap 11 with the first element (64).
• The array now becomes: [11, 25, 12, 22, 64].

2. Second Pass :
• The unsorted portion is [25, 12, 22, 64].
• Find the minimum element in this part: 12.
• Swap 12 with the first element of the unsorted part (25).
• The array now becomes: [11, 12, 25, 22, 64].

3. Third Pass :
• The unsorted portion is [25, 22, 64].
• Find the minimum element: 22.
• Swap 22 with the first element of the unsorted part (25).
• The array now becomes: [11, 12, 22, 25, 64].
4. Fourth Pass :
• The unsorted portion is [25, 64].
• The minimum element is 25, which is already in the correct position, so no swap is needed.
• The array remains : [11, 12, 22, 25, 64].

5. Fifth Pass :
• Only one element is left (64), and it is already in the correct position.

Now, at the end of the sorting process, the array is sorted : [11, 12, 22, 25, 64]

f) Explain Insertion sort technique with an example.


Ans: Insertion Sort is a simple and efficient comparison-based sorting algorithm that builds the
final sorted array one item at a time. It is much like sorting playing cards in your hands. The idea
is to take each element from the unsorted part of the list and insert it into its correct position in
the sorted part of the list. The sorted part of the list grows gradually from left to right as the
algorithm progresses.

• How Insertion Sort Works :


1. Start with the second element (since the first element is trivially sorted by itself).
2. Compare the current element with the elements before it (in the sorted portion of the list).
3. Shift the elements that are greater than the current element one position to the right.
4. Insert the current element into its correct position in the sorted portion of the list.
5. Repeat this process for all elements in the array.

• Steps of the Insertion Sort Algorithm :


1. Begin with the second element of the array.
2. Compare it with the elements before it.
3. Shift all larger elements to the right.
4. Insert the current element into its correct position.
5. Repeat the process for the next element.

• Example of Insertion Sort :


Let’s consider an example where the array to be sorted is : [5, 2, 9, 1, 5, 6]
Step-by-Step Process:

1. First Pass (i = 1) :
• Compare the second element (2) with the first element (5).
• Since 2 < 5, we shift 5 to the right and place 2 in its correct position.
• The array becomes : [2, 5, 9, 1, 5, 6].

2. Second Pass (i = 2) :
• Compare the third element (9) with the previous element (5).
• Since 9 > 5, no shifting is required. 9 stays in its position.
• The array remains : [2, 5, 9, 1, 5, 6].
3. Third Pass (i = 3) :
• Compare the fourth element (1) with the previous elements.
• Since 1 < 9, we shift 9 to the right.
• Since 1 < 5, we shift 5 to the right.
• Since 1 < 2, we shift 2 to the right.
• Insert 1 in the first position.
• The array becomes : [1, 2, 5, 9, 5, 6].

4. Fourth Pass (i = 4) :
• Compare the fifth element (5) with the previous elements.
Since 5 < 9, we shift 9 to the right.
• Since 5 == 5, no further shifting is needed, and 5 stays in its position.
• The array becomes : [1, 2, 5, 5, 9, 6].

5. Fifth Pass (i = 5) :
• Compare the sixth element (6) with the previous elements.
• Since 6 < 9, we shift 9 to the right.
• Since 6 > 5, no further shifting is needed, and 6 is inserted in its correct position.
• The array becomes : [1, 2, 5, 5, 6, 9].

Now, After all passes, the array is fully sorted : [1, 2, 5, 5, 6, 9]

g) What is a circular queue? How is it differ from a static queue ?


Ans: A Circular Queue is a variation of the regular queue where the last position is connected
back to the first position to form a circle. It is also known as a Ring Buffer. In a circular queue,
when the rear of the queue reaches the end of the array, it can wrap around and start filling the
positions that have already been vacated by the front of the queue. This helps in utilizing the
space more efficiently, especially in situations where elements are dequeued frequently and
there is a need to reuse the free space.

• Circular Queue vs Static Queue :

A Static Queue (also known as a regular or linear queue) is a queue where the elements are
arranged in a linear fashion. The main difference between a Circular Queue and a Static Queue
lies in how they manage the available space and how elements are added and removed.

• Key Differences :
Points Circular Queue Static Queue (Linear Queue)

1. Space Efficient space utilization. Once Can result in wasted space,


Utilisation elements are dequeued, space especially when elements are
can be reused. dequeued but not re-used until the
queue is reset.

2. Queue Overflow occurs only when the Overflow occurs when the queue is
Overflow queue is full, considering the full, regardless of available empty
circular nature. spaces at the front.

3. Wrap Around The rear wraps around to the front The rear cannot wrap around. Once
when it reaches the end of the the queue is full, no new elements
queue. can be added, even if space is
available at the front.

4. Implementation More complex to implement, Easier to implement, straightforward


requires maintaining front and rear front and rear pointers.
pointers and wrapping them
around.

5. Queue Size Fixed size, but with efficient usage Fixed size, but space is wasted as
of space (no wasted space when elements are dequeued and no
elements are removed). longer reused.

h) Explain different types of AVL rotations with an example.


Ans:
1. In an AVL Tree (Adelson-Velsky and Landis Tree), a self-balancing binary search tree (BST),
rotations are performed to maintain the balance property after insertion or deletion operations.
The balance factor of each node in the tree is calculated as the difference between the height of
the left subtree and the right subtree :
• Balance Factor = Height of Left Subtree - Height of Right Subtree
2. The AVL tree requires that the balance factor of every node must be between -1 and 1. If at
any point the balance factor of a node becomes less than -1 or greater than 1, the tree becomes
unbalanced, and rotations are used to restore the balance.

• Types of AVL Rotations : There are four types of AVL rotations used to balance the tree when
it becomes unbalanced :
1. Right Rotation (Single Rotation) : This is performed when the left subtree of the left child is
too tall (Left-Left case).
2. Left Rotation (Single Rotation) : This is performed when the right subtree of the right child is
too tall (Right-Right case).
3. Left-Right Rotation (Double Rotation) : This is performed when the right subtree of the left
child is too tall (Left-Right case).
4. Right-Left Rotation (Double Rotation) : This is performed when the left subtree of the right
child is too tall (Right-Left case).
Q3) Attempt any Four of the following. [4 × 4 = 16]

a) Write a function to create & display singly linked lists.


Ans:
class Node:
def __init__(self, data):
self.data = data
self.next = None

class SinglyLinkedList:
def __init__(self):
self.head = None

def insert(self, data):


new_node = Node(data)
if not self.head:
self.head = new_node
else:
current = self.head
while current.next:
current = current.next
current.next = new_node

def display(self):
current = self.head
while current:
print(current.data, end=" -> ")
current = current.next
print("None")

# Example usage
ll = SinglyLinkedList()
ll.insert(10)
ll.insert(20)
ll.insert(30)
ll.display()

#Output: 10 -> 20 -> 30 -> None


b) Write a function to insert an element into a queue, in which the queue is implemented as an
array.
Ans:
class Queue:
def __init__(self, size):
self.size = size
self.queue = [None] * size # Initialize an array with None
self.front = -1
self.rear = -1

def enqueue(self, data):


if self.rear == self.size - 1:
print("Queue is full")
else:
if self.front == -1: # If the queue is empty
self.front = 0
self.rear += 1
self.queue[self.rear] = data
print(f"Enqueued: {data}")

def display(self):
if self.front == -1:
print("Queue is empty")
else:
for i in range(self.front, self.rear + 1):
print(self.queue[i], end=" ")
print()

# Example usage
q = Queue(5)
q.enqueue(10)
q.enqueue(20)
q.enqueue(30)
q.display() # Output: 10 20 30

Output :
Enqueued: 10
Enqueued: 20
Enqueued: 30
10 20 30
c) Explain BFS traversing technique with an example.
Ans:
• BFS (Breadth-First Search) Traversing Technique : BFS is a graph traversal algorithm that
explores all the vertices of a graph level by level. It starts from the root (or any arbitrary node)
and explores all its neighbors first, before moving on to the next level of nodes. BFS is
implemented using a queue data structure to manage the exploration order.

• Steps in BFS Traversal :


1. Start at the root node (or any arbitrary node).
2. Enqueue the starting node and mark it as visited.
3. While the queue is not empty :
• Dequeue a node from the front of the queue.
• Visit and process the current node (i.e., print or record it).
• Enqueue all unvisited neighbors of the current node and mark them as visited.

• BFS Algorithm :
1. Initialize an empty queue and enqueue the starting node.
2. Mark the starting node as visited.
3. While the queue is not empty :
• Dequeue a node.
• Visit the node (process or print).
• Enqueue all its unvisited neighbors and mark them as visited.

• BFS Example : Let's demonstrate BFS traversal using a simple graph :


Consider the following graph :
A
/\
B C
/\ \
D E F
Here, the graph is undirected, and we will start BFS traversal from node 'A'.
BFS Traversal of this Graph :

1. Start at A :
• Queue : [A]
• Visited : {A}
• Process A and enqueue its neighbors B and C.
• Queue : [B, C]

2. Dequeue B :
• Dequeue : [C]
• Visited : {A, B}
• Process B and enqueue its neighbors D and E (A is already visited).
• Queue : [C, D, E]
3. Dequeue C :
• Queue : [D, E]
• Visited : {A, B, C}
• Process C and enqueue its neighbor F.
• Queue : [D, E, F]

4. Dequeue D :
• Queue : [E, F]
• Visited : {A, B, C, D}
• D has no unvisited neighbors.

5. Dequeue E :
• Queue : [F]
• Visited : {A, B, C, D, E}
• E has no unvisited neighbors.

6. Dequeue F :
• Queue : [ ]
• Visited : {A, B, C, D, E, F}
• F has no unvisited neighbors.

Now, the queue is empty, and the BFS traversal is complete.


• BFS Traversal Result : A -> B -> C -> D -> E -> F

d) Write an algorithm to convert infix expression to postfix expression.


Ans:
• Infix to Postfix Conversion Algorithm :
1. In infix notation, operators are written between operands, like A + B. In postfix notation (also
known as Reverse Polish Notation or RPN), operators are written after operands, like A B +.
2. To convert an infix expression to postfix, we use a stack data structure to help reorder the
operators and operands.
• Algorithm to Convert Infix to Postfix :
1. Initialize an empty stack for operators and an empty list (or string) for the result (postfix
expression).
2. Process the infix expression from left to right, character by character :
• Operand (number/variable) : Directly append it to the result list.
• Left Parenthesis ( :- Push it onto the stack.
• Right Parenthesis ) :- Pop from the stack and append to the result until a left parenthesis ( is
encountered on the stack. Pop and discard the left parenthesis.
• Operator (+, -, *, /, etc.) :- Pop operators from the stack to the result list while they have higher
or equal precedence than the current operator. Then, push the current operator onto the stack.
3. After reading the entire infix expression, pop all the operators from the stack and append
them to the result list.
e) Write a function to delete the first node from a singly linked list.
Ans:
class Node:
def __init__(self, data):
self.data = data
self.next = None

class SinglyLinkedList:
def __init__(self):
self.head = None

def delete_first_node(self):
if self.head:
self.head = self.head.next
else:
print("List is empty.")

def display(self):
current = self.head
while current:
print(current.data, end=" -> ")
current = current.next
print("None")

# Example usage
ll = SinglyLinkedList()
ll.head = Node(10)
ll.head.next = Node(20)
ll.head.next.next = Node(30)

print("Before deletion:")
ll.display()

ll.delete_first_node()

print("After deletion:")
ll.display()

Output :
Before deletion : 10 -> 20 -> 30 -> None
After deletion : 20 -> 30 -> None
f) Write a function to reverse a string using stack.
Ans:
def reverse_string(s):
stack = [] # Stack to store characters

# Push each character of the string onto the stack


for char in s:
stack.append(char)

# Pop characters from the stack and build the reversed string
reversed_str = ""
while stack:
reversed_str += stack.pop()

return reversed_str

# Example usage
string = "Hello, World!"
reversed_string = reverse_string(string)
print("Original String:", string)
print("Reversed String:", reversed_string)

Output :
Original String : Hello, World!
Reversed String : !dlroW ,olleH
g) Write a ‘C’ Program for evaluation of polynomials.
Ans:
#include <stdio.h>

// Function to evaluate the polynomial at given x using Horner's method


double evaluate_polynomial(int coef[], int n, double x) {
double result = coef[0];
for (int i = 1; i <= n; i++) {
result = result * x + coef[i];
}
return result;
}
int main() {
int n;
printf("Enter degree of polynomial: ");
scanf("%d", &n);

int coef[n + 1];


printf("Enter coefficients from highest degree to constant term:\n");
for (int i = 0; i <= n; i++) {
scanf("%d", &coef[i]);
}
double x;
printf("Enter value of x: ");
scanf("%lf", &x);

printf("Polynomial value at x = %.2f: %.2f\n", x, evaluate_polynomial(coef, n, x));


return 0;
}

Q4) Attempt any Four of the following: [4 × 4 = 16]

a) Construct an AVL tree of following data.


20, 10, 30, 5, 15, 25, 35, 13, 17
b) Construct Binary search tree for following data.
78, 95, 2, 57, 13, 29, 61, 10
c) Sort the following data by using selection sort
12, 11, 13, 5, 6
d) Construct an AVL tree for following sequential data :
Jan, Feb, Apr, May, July, Aug, June.
e) Use merge sort technique on following data:
45, 85, 96, 78, 34, 12, 49, 38, 18.
f) Construct Binary search tree of following data :
RAM, SITA, AMIT, JOEL, IVAN, ASHA.
g) What is a circular queue ? Explain it with an example.
Ans: A circular queue is a type of queue in which the last position is connected back to the first
position, forming a circular structure. This design helps optimize space utilization, as once an
element is dequeued, the space it occupies becomes available for new elements, even if the
queue is not entirely empty.

• Key Characteristics :
1. Fixed Size : A circular queue has a fixed size.
2. Front and Rear Pointers : It maintains two pointers—front (points to the first element) and rear
(points to the last element).
3. Wrap-around : When the rear pointer reaches the end of the queue, it wraps around to the
beginning, allowing for efficient use of space.

• Operations in a Circular Queue :


1. Enqueue : Adds an element at the rear.
2. Dequeue : Removes an element from the front.
3. Front : Returns the element at the front without removing it.
4. Rear : Returns the element at the rear.

• Example : Consider a circular queue of size 5 with the following operations :

1. Initial Queue (size 5) : Front = -1, Rear = -1


Queue : [empty, empty, empty, empty, empty]

2. Enqueue(10) : Front = 0, Rear = 0


Queue : [10, empty, empty, empty, empty]

3. Enqueue(20) : Front = 0, Rear = 1


Queue : [10, 20, empty, empty, empty]

4. Enqueue(30) : Front = 0, Rear = 2


Queue : [10, 20, 30, empty, empty]

5. Dequeue() (removes 10) : Front = 1, Rear = 2


Queue : [empty, 20, 30, empty, empty]

6. Enqueue(40) : Front = 1, Rear = 3


Queue : [empty, 20, 30, 40, empty]

7. Enqueue(50) : Front = 1, Rear = 4


Queue: [empty, 20, 30, 40, 50]

8.Enqueue(60)(wraps around to index 0, because the queue is full): Front = 1, Rear = 0


Queue: [60, 20, 30, 40, 50]
h) What is Graph? Explain its representation techniques in detail.
Ans: A graph is a data structure consisting of a collection of nodes (also called vertices) and
edges (connections between the nodes). It is used to represent relationships, connections, or
pathways between entities. Graphs are widely used in computer science to model real-world
systems such as social networks, maps, computer networks, recommendation systems, etc.

• Representation Techniques of Graphs : There are several ways to represent graphs in


memory, each with its own advantages and trade-offs. The most common methods are
Adjacency Matrix, Adjacency List, Incidence Matrix, and Edge List.

1. Adjacency Matrix : An adjacency matrix is a 2D array (or matrix) used to represent a graph.
The rows and columns represent the vertices, and the values in the matrix represent the
presence or absence of edges.
• In a directed graph, if there is an edge from vertex to vertex , then the matrix entry is 1 (or the
weight of the edge). Otherwise, it is 0.
• In an undirected graph, the matrix is symmetric, meaning if there is an edge from vertex to
vertex , both will be 1.

2. Adjacency List : An adjacency list is a collection of lists or arrays where each list represents a
vertex and contains a list of its adjacent vertices (neighbors).
• For a directed graph, the list at index will contain all the vertices to which vertex has directed
edges.
• For an undirected graph, each edge is stored twice, once for each vertex involved.

3. Incidence Matrix : An incidence matrix represents a graph using a matrix where rows
represent vertices and columns represent edges. The entry at is 1 if vertex is incident to edge ,
and 0 otherwise.
• For a directed graph, if vertex is the starting point of edge , then , and if vertex is the
endpoint, then .
• For an undirected graph, if the vertex is incident to edge , then .

4. Edge List : An edge list is a simple list of all the edges in the graph. Each edge is represented
by a pair (or triplet, if the graph is weighted) of vertices.
i) Write a C- program to display a linked list in Reverse order.
Ans:
#include <stdio.h>
#include <stdlib.h>
// Define the structure for the node
struct Node {
int data;
struct Node *next;
};
// Function to insert a node at the end of the linked list
void insertEnd(struct Node **head, int data) {
struct Node *newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
if (*head == NULL) *head = newNode;
else {
struct Node *temp = *head;
while (temp->next) temp = temp->next;
temp->next = newNode;
} }
// Function to print the linked list in reverse order using recursion
void printReverse(struct Node *head) {
if (head) {
printReverse(head->next);
printf("%d ", head->data);
} }
int main() {
struct Node *head = NULL;
int n, val;
// Input number of nodes and the values
printf("Enter number of nodes: ");
scanf("%d", &n);
while (n--) {
scanf("%d", &val);
insertEnd(&head, val);
}
// Display the list in reverse order
printReverse(head);
printf("\n");
return 0; }

Input : Enter number of nodes : 3


123
Output : 3 2 1
Q5) Attempt any TWO of the following. [2×3=6]

a) Define the following terms :


i) Directed Graph.
ii) Strict Binary Tree.
iii) Cyclic Graph.
Ans:
i) Directed Graph : A directed graph (or digraph) is a graph in which the edges have a direction.
Each edge is represented by an ordered pair of vertices, where the first vertex is the source,
and the second vertex is the target. The direction of the edge is indicated by an arrow pointing
from the source to the target vertex.
ii) Strict Binary Tree : A strict binary tree (also known as a proper binary tree) is a type of binary
tree where every node has either 0 or 2 children. No node in a strict binary tree can have only
one child.
iii) Cyclic Graph : A cyclic graph is a graph that contains at least one cycle. A cycle in a graph is
a path in which the first and last vertices are the same, and all other vertices are distinct. A
graph is cyclic if it contains such a closed loop or cycle.

b) Convert the following expression into postfix:


i) A/B $ CD * E - A *C
ii) (A + B * C -D)/ E $ F
Ans:
i) A/B $ CD * E - A * C :
-
Infix expression : A/B $ CD * E - A * C
1. A/B : Divide first.
2. $ is a higher precedence operator than * and /, so we need to handle it first.
3. CD * E : Multiplication.
4. A * C : Multiplication.
5. - is lower precedence than $.
Postfix expression : A B / C D * E * - A C * -

ii) (A + B * C - D) / E $ F :
-
Infix expression : (A + B * C - D) / E $ F
1. B * C : First multiplication.
2. A + (B * C) : Addition.
3. (A + B * C - D) : Subtraction.
4. / E : Division.
5. $ F : Exponentiation.
Postfix expression : A B C * + D - E / F $
c) Convert the following expression into prefix
i) A+B/C*(D – A) ^ F ^ H
ii) A* (B*C+D*E) + F
Ans:
i) A+B/C*(D – A) ^ F ^ H :
-
Infix expression : A + B / C * (D - A) ^ F ^ H
1. B / C : Division.
2. D - A : Subtraction.
3. (D - A) ^ F : Exponentiation.
4. (D - A) ^ F ^ H : Exponentiation (right to left).
5. B / C * (D - A) ^ F ^ H : Multiplication.
6. A + (result from step 5) : Addition.
Prefix expression : + A * / B C ^ - D A ^ F H

ii) A * (B * C + D * E) + F :
-
Infix expression : A * (B * C + D * E) + F
1. B * C : Multiplication.
2. D * E : Multiplication.
3. B * C + D * E : Addition.
4. A * (result from step 3) : Multiplication.
5. A * (B * C + D * E) + F : Addition.
Prefix expression : + * A + * B C * D E F

d) Define the following terms:


i) Parent Node.
ii) Sub tree.
iii) Directed Graph.
Ans:
i) Parent Node : A parent node is a node in a tree that has one or more child nodes. It is a node
that directly connects to one or more other nodes (children). In a binary tree, a node can have at
most two children: a left child and a right child.
ii) Subtree : A subtree is a tree formed by a node and all of its descendants. In other words, for
any node in a tree, the subtree rooted at that node consists of that node and all the nodes that
are connected beneath it (direct or indirect children).
iii) Directed Graph : A directed graph (or digraph) is a graph in which edges have a direction.
Each edge is represented as an ordered pair of vertices, where each edge goes from a source
vertex to a target vertex. Directed graphs are used to represent relationships with direction,
such as roads in a one-way street, or links between web pages where direction matters.

You might also like