Dsa Model 1 With Answer
Dsa Model 1 With Answer
return 0;
}
2. A task manager uses a linked list to store user tasks. A new task is added at the beginning of the
list for immediate execution, and the list needs to be updated.Write a function to insert a node at
the beginning of a linked list.
Linked List: 11 7 3
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node;
Node* createNode(int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
if (!newNode) {
printf("Memory allocation failed.\n");
exit(1);
}
newNode->data = data;
newNode->next = NULL;
return newNode;
}
return 0;
}
4. A library system uses a linked list to track borrowed books. The program counts the number of
books currently borrowed, stored as nodes in the linked list.Write a Cprogram to count the
number of nodes in a linked list
Number of nodes: 1
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
char bookName[50];
struct Node* next;
} Node;
Node* createNode(char* bookName) {
Node* newNode = (Node*)malloc(sizeof(Node));
if (!newNode) {
printf("Memory allocation failed.\n");
exit(1);
}
snprintf(newNode->bookName, sizeof(newNode->bookName), "%s", bookName);
newNode->next = NULL;
return newNode;
}
int countNodes(Node* head) {
int count = 0;
while (head != NULL) {
count++;
head = head->next;
}
return count;
}
int main() {
Node* head = createNode("Introduction to C Programming");
printf("Number of nodes: %d\n", countNodes(head));
free(head);
return 0;
}
5. A code editor needs to verify if a user's mathematical expression contains properly balanced
parentheses. The program checks the expression using a stack to ensure all parentheses
match.Design a C program to check for balanced parentheses using a stack.
Enter an expression: (j + k) * (l – m)
Balanced
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#define MAX_SIZE 100
typedef struct {
char items[MAX_SIZE];
int top;
} Stack;
void initializeStack(Stack* stack) {
stack->top = -1;
}
bool isStackEmpty(Stack* stack) {
return stack->top == -1;
}
bool isStackFull(Stack* stack) {
return stack->top == MAX_SIZE - 1;
}
bool push(Stack* stack, char value) {
if (isStackFull(stack)) {
printf("Error: Stack overflow while pushing '%c'\n", value);
return false;
}
stack->items[++stack->top] = value;
return true;
}
char pop(Stack* stack) {
if (isStackEmpty(stack)) {
printf("Error: Stack underflow while popping\n");
return '\0';
}
return stack->items[stack->top--];
}
bool isMatchingPair(char opening, char closing) {
return (opening == '(' && closing == ')') ||
(opening == '{' && closing == '}') ||
(opening == '[' && closing == ']');
}
bool areParenthesesBalanced(char* expression) {
Stack stack;
initializeStack(&stack);
for (int i = 0; expression[i] != '\0'; i++) {
char currentChar = expression[i];
if (currentChar == '(' || currentChar == '{' || currentChar == '[') {
if (!push(&stack, currentChar)) {
return false; // Stop if push fails
}
}
else if (currentChar == ')' || currentChar == '}' || currentChar == ']') {
if (isStackEmpty(&stack)) {
return false; // Unmatched closing parenthesis
}
char topChar = pop(&stack);
if (!isMatchingPair(topChar, currentChar)) {
return false; // Mismatched parentheses
}
}
}
return isStackEmpty(&stack);
}
int main() {
char expression[MAX_SIZE];
#include <stdio.h>
#include <stdbool.h>
// Main function
int main() {
Queue queue;
initializeQueue(&queue);
// Enqueue and dequeue operations
enqueue(&queue, 3);
enqueue(&queue, 7);
enqueue(&queue, 10);
displayQueue(&queue);
dequeue(&queue);
displayQueue(&queue);
enqueue(&queue, 5);
displayQueue(&queue);
dequeue(&queue);
displayQueue(&queue);
return 0;
}
7. A student registration system needs to manage a list of student IDs for a course. The program
collects and displays the student IDs in the order they are entered into the list
Write a program in C to create and display a Singly Linked List.
Test Data :
Input the number of nodes : 3
Input data for node 1 : 5
Input data for node 2 : 6
Input data for node 3 : 7
Expected Output :
Data entered in the list :
Data = 5 ,Data = 6 , Data = 7
#include <stdio.h>
#include <stdlib.h>
if (head == NULL) {
head = newNode; // First node becomes the head
} else {
temp->next = newNode; // Link the new node to the previous one
}
temp = newNode; // Update the temp pointer to the new node
}
return head;
}
// Main function
int main() {
int n;
displayLinkedList(head);
return 0;
}
8. A grading system stores student scores in an array. The program sorts the scores in ascending
order to display the students from lowest to highest score.Write a program in C to sort elements
of an array in ascending order.
Test Data :
Input the size of array : 5
Input 5 elements in the array :
Element – 0 : 2 , Element – 1 : 7 ,Element – 2 : 4 ,Element – 3 : 5, Element – 4 : 9
Expected Output :
Elements of array in sorted ascending order:
24579
#include <stdio.h>
// Main function
int main() {
int size;
int arr[size];
printf("Input %d elements in the array:\n", size);
for (int i = 0; i < size; i++) {
printf("Element - %d: ", i);
scanf("%d", &arr[i]);
}
return 0;
}
9. A patient management system stores patient data in two sorted lists based on age groups. The
program merges these two lists to create one comprehensive sorted list.Write a C program to
merge two sorted singly linked lists into a single sorted linked list.
return mergedList;
}
// Main function
int main() {
Node* list1 = NULL;
Node* list2 = NULL;
return 0;
}
10. A text editor program uses a stack to reverse a user-inputted string to support undo
functionality. The reversed string is displayed as output.Write a C program that accepts a string
and reverse it using a stack.
Expected Output:
Input a string: data
Reversed string using a stack is:atad
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_SIZE 100 // Define the maximum size for the stack
// Main function
int main() {
char str[MAX_SIZE];
reverseString(str);
return 0;
}
11. A customer service center uses a queue to handle incoming service requests. The program
reverses the order of service requests to process the most recent ones first.Write a C program to
reverse the elements of a queue.
Expected Output:
Queue elements are:6 7 8 9
Reverse Queue, elements are:9 8 7 6
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100 // Define the maximum size for the queue
// Main function
int main() {
Queue q;
initializeQueue(&q);
return 0;
}
12. A shopping cart application stores the prices of items in an array. The program calculates and
displays the total cost of all the items in the cart.Write a program in C to find the sum of all
elements of the array.
Test Data :
Input the number of elements to be stored in the array :3
Input 3 elements in the array :
Element – 0 : 2 , Element – 1 : 5 , Element - 2 : 8
Expected Output :
Sum of all elements stored in the array is : 15
#include <stdio.h>
int main() {
int n, sum = 0;
printf("Input the number of elements to be stored in the array: ");
scanf("%d", &n);
int arr[n];
for (int i = 0; i < n; i++) {
printf("Element - %d : ", i);
scanf("%d", &arr[i]);
}
for (int i = 0; i < n; i++) {
sum += arr[i];
}
printf("Sum of all elements stored in the array is: %d\n", sum);
return 0;
}
13. A student data system manages student records in two separate lists based on enrolment periods.
The program merges these lists into one, keeping the students ordered by their enrolment
dates.Write a C program to merge two sorted singly linked lists into a single sorted linked list.
Test Data and Expected Output :
Two sorted singly linked lists:
1357
2 46
After merging the said two sorted lists: 1 2 3 4 5 6 7.
#include <stdio.h>
#include <stdlib.h>
return dummy.next;
}
// Main function
int main() {
// Create first sorted list: 1 -> 3 -> 5 -> 7
struct Node* list1 = createNode(1);
list1->next = createNode(3);
list1->next->next = createNode(5);
list1->next->next->next = createNode(7);
return 0;
}
14. A customer service system handles incoming customer requests using a queue. As customers are
served, their requests are dequeued, and new requests are inserted at the rear of the queue.Write
a C program to implement a queue using an array. Programs should contain functions for
inserting elements into the queue, displaying queue elements, and checking whether the queue is
empty or not.
Expected Output:
Initialize a queue!
Check the queue is empty or not? Yes
Insert some elements into the queue:
Queue elements are: 1 2 3
Insert another element into the queue:
Queue elements are: 1 2 3 4
Check the queue is empty or not? No
#include <stdio.h>
#include <stdlib.h>
// Main function
int main() {
Queue q;
initializeQueue(&q);
return 0;
}
15. A task management application stores pending tasks in a queue. The program sorts tasks based
on priority, ensuring that the highest priority tasks are processed first.Write a C program to sort
the elements of a queue in ascending order.
Expected Output:
return 0;
}
16. An equation solver uses an expression tree to solve mathematical postfix expressions. The
program takes an input expression, constructs the tree, and outputs the evaluated result.Write a
C program to build an expression tree from a postfix expression. Evaluate and display the results.
Enter a postfix expression: 23+5*
In-order Traversal of the Expression Tree: 2 + 3 * 5
Result: 25
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
switch (root->data) {
case '+': return leftValue + rightValue;
case '-': return leftValue - rightValue;
case '*': return leftValue * rightValue;
case '/': return leftValue / rightValue;
default: return 0;
}
}
if (isdigit(current)) {
// If the character is a number, create a node and push to stack
push(&stack, createNode(current));
} else if (isOperator(current)) {
// If the character is an operator, pop two nodes, create a new node and push it back
Node* operatorNode = createNode(current);
operatorNode->right = pop(&stack);
operatorNode->left = pop(&stack);
push(&stack, operatorNode);
}
}
// The final node in the stack will be the root of the expression tree
return pop(&stack);
}
// Main function
int main() {
char postfixExpression[100];
17. An e-commerce platform sorts product prices using merge sort. The program takes unsorted
prices, sorts them in ascending order, and displays the sorted list of product prices.Write a C
program to sort a list of elements using the merge sort algorithm.
Sample Output:
Given array is :125 181 130 25 61 887
Sorted array is : 25 61 125 130 181 887
#include <stdio.h>
// Main function
int main() {
int arr[] = {125, 181, 130, 25, 61, 887}; // Sample array of product prices
int n = sizeof(arr) / sizeof(arr[0]);
printf("Given array is: ");
mergeSort(arr, 0, n - 1);
printf("Sorted array is: ");
printArray(arr, n);
return 0;
}
18. A network optimization tool uses Prim’s algorithm to find the minimum spanning tree. The
program calculates the most cost-efficient way to connect all nodes in the network with the least
total cost.Write a C program that implements Prim’s algorithm to find the minimum spanning
#define MAX_VERTICES 10
return 0;
}
19. A task scheduling system uses a stack implemented with two queues. The program pushes tasks
onto the stack using two queues and pops tasks off the stack to process them in reverse order.
Write a C program to implement a stack using two queues.
Push data 1
Push data 2
Push data 3
Pop data: 3
Pop data: 2
Pop data: 1
#include <stdio.h>
#include <stdlib.h>
return root;
}
if (root->data == key) {
return 1; // Found
}
21. A queue management system for parking slots operates as a circular queue. Cars enter (insert)
and exit (delete) in a circular manner, ensuring efficient management of parking spaces. Write a
C program to implement a circular queue and perform insertion and deletion operations.
Circular Queue:
Front 1 2 3 4 5 Rear
After Insertion:
Front 1 2 3 4 5 6 Rear
After Deletion:
Front 2 3 4 5 6 Rear
#include <stdio.h>
#include <stdlib.h>
queue->arr[queue->rear] = value;
printf("Inserted %d into the queue\n", value);
}
return 0;
}
22. A mathematical expression evaluator uses stacks to convert infix expressions to postfix format.
The program then evaluates the postfix expression to compute the result of complex
mathematical operations.Write a C program to convert an infix expression to a postfix expression
using a stack.
Infix Expression: (3 + 5) * 2 / (7 - 4)
Postfix Expression: 3 5 + 2 * 7 4 - /
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
// Stack structure
struct Stack {
char arr[MAX];
int top;
};
// Function to initialize the stack
void initStack(struct Stack *stack) {
stack->top = -1;
}
infixToPostfix(infix, postfix);
return 0;
}
23. A customer service system implements a queue using two stacks. The program uses two stacks to
enqueue and dequeue customers efficiently, ensuring the first customer in is the first to be
served.Write a C program to implement a queue using two stacks.
Enqueue data 1
Enqueue data 2
Enqueue data 3
Dequeue data: 1
Dequeue data: 2
Dequeue data: 3
#include <stdio.h>
#include <stdlib.h>
// Main function
int main() {
struct Queue queue;
initQueue(&queue);
// Enqueue data
enqueue(&queue, 1);
enqueue(&queue, 2);
enqueue(&queue, 3);
// Dequeue data
dequeue(&queue);
dequeue(&queue);
dequeue(&queue);
return 0;
}
24. A program sorts employee ID numbers using the shell sort algorithm, which efficiently sorts an
array by comparing and swapping elements at intervals, improving on basic sorting techniques
like bubble sort.Write a C program to implement the shell sort algorithm.
Original Array: 6 2 9 5 7
// Shift earlier gap-sorted elements up until the correct location for arr[i] is found
while (j >= gap && arr[j - gap] > temp) {
arr[j] = arr[j - gap];
j -= gap;
}
arr[j] = temp;
}
}
}
int main() {
int arr[] = {6, 2, 9, 5, 7}; // Original array
int n = sizeof(arr) / sizeof(arr[0]);
return 0;
}
25. A report generation system sorts transaction amounts using merge sort. The program takes a
large list of unsorted transaction amounts, applies merge sort, and produces the sorted list for
further analysis.Write a C program to implement the merge sort algorithm.
Original Array: 4 1 7 3 9
After Merge Sort:
13479
#include <stdio.h>
int main() {
int arr[] = {4, 1, 7, 3, 9}; // Original array
int n = sizeof(arr) / sizeof(arr[0]);
return 0;
}
26. A priority queue in a task management system uses heap sort to organize tasks based on priority.
The program sorts tasks using heap sort, ensuring the highest priority tasks are processed
first.Write a C program to implement the heap sort algorithm.
Original Array: 5 9 3 1 7
After Heap Sort:
13579
#include <stdio.h>
int main() {
int arr[] = {5, 9, 3, 1, 7}; // Original array
int n = sizeof(arr) / sizeof(arr[0]);
printf("Original Array: ");
printArray(arr, n);
heapSort(arr, n);
printf("After Heap Sort: ");
printArray(arr, n);
return 0;
}
27. A navigation system calculates the shortest path between two locations using Dijkstra’s
algorithm. The program processes the weighted map and provides the optimal route, considering
distance or travel time.Write a C program to implement Dijkstra's algorithm for finding the
shortest path in a weighted graph.
#include <stdio.h>
#include <limits.h>
int main() {
// Graph represented as an adjacency matrix
int graph[V][V] = {
{0, 4, 0, 0, 0, 0, 0, 8, 0},
{4, 0, 8, 0, 0, 0, 0, 0, 0},
{0, 8, 0, 7, 0, 4, 0, 0, 2},
{0, 0, 7, 0, 9, 14, 0, 0, 0},
{0, 0, 0, 9, 0, 10, 0, 0, 0},
{0, 0, 4, 14, 10, 0, 2, 0, 0},
{0, 0, 0, 0, 0, 2, 0, 1, 6},
{8, 0, 0, 0, 0, 0, 1, 0, 7},
{0, 0, 2, 0, 0, 0, 6, 7, 0}
};
int source = 0; // Source vertex (can be changed)
dijkstra(graph, source);
return 0;
}
28. A network design system uses Kruskal's algorithm to find the minimal connection cost between
various data nodes. The program calculates the minimum spanning tree of the network,
optimizing installation costs.Write a C program to implement kruskal's algorithm for finding the
shortest path in a weighted graph
#include <stdio.h>
#include <stdlib.h>
if (rootX != rootY) {
// Union by rank
if (subsets[rootX].rank < subsets[rootY].rank) {
subsets[rootX].parent = rootY;
} else if (subsets[rootX].rank > subsets[rootY].rank) {
subsets[rootY].parent = rootX;
} else {
subsets[rootY].parent = rootX;
subsets[rootX].rank++;
}
}
}
// Function to implement Kruskal's Algorithm
void kruskal(struct Edge edges[], int V, int E) {
struct Edge result[V]; // Store the final MST
int e = 0; // Count of edges in MST
int i = 0; // Initial index of sorted edges
struct Subset subsets[V]; // Subsets for union-find
// If including this edge does not cause a cycle, include it in the result
if (x != y) {
result[e++] = nextEdge;
unionSets(subsets, x, y);
}
}
// Main function
int main() {
int V = 4; // Number of vertices
int E = 5; // Number of edges
return 0;
}
29. An inventory management system uses closed hashing to handle product IDs. The program
handles collisions by using a fixed table size and a hashing function to resolve conflicts and
maintain fast lookups, insertions, and deletions.Design a program for closed hashing to resolving
the collision. Implement the insertion, deletion and searching operations.
Note:
Choose your fixed table size
hashIndex = key % Table size
#include <stdio.h>
#include <stdlib.h>
return 0;
}
30. Design a C program for Binary Search Tree ADT operations. The operations are insertion, find
minimum and find maximum and display.
#include <stdio.h>
#include <stdlib.h>
if (minNode != NULL) {
printf("Minimum value in the BST: %d\n", minNode->data);
} else {
printf("The BST is empty.\n");
}
if (maxNode != NULL) {
printf("Maximum value in the BST: %d\n", maxNode->data);
} else {
printf("The BST is empty.\n");
}
return 0;
}