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

dsa

Uploaded by

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

dsa

Uploaded by

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

DATA STRUCTURES A

CODE SNIPPET
1 (a) Write a program to find the maximum element in each row of the matrix using
pointers.
#include<stdio.h>

// Function to find the maximum element in a row of a matrix


// Parameters: pointer to the row (arr), number of columns (m)
int findMax(int *arr, int m) {
int max = -1; // Initialize max to -1 (assuming all elements are non-negative)

for (int i = 0; i < m; i++) { // Iterate through all columns in the row
if (max < *arr) { // If the current element is greater than max
max = *arr; // Update max to the current element
}
arr++; // Move pointer to the next element in the row
}

return max; // Return the maximum value found in the row


}

int main() {
int n, m, mat[10][10]; // Variables for matrix dimensions and the matrix itself

// Prompt user to enter the size of the matrix


printf("Enter the size of the matrix (rows and columns):\n");
scanf("%d%d", &n, &m);

// Prompt user to enter the elements of the matrix


printf("Enter the elements of the matrix:\n");
for (int i = 0; i < n; i++) { // Loop through rows
for (int j = 0; j < m; j++) { // Loop through columns
scanf("%d", &mat[i][j]); // Input each element
}
}

// Find and print the maximum element of each row


for (int i = 0; i < n; i++) {
int ans = findMax(mat[i], m); // Call findMax function for the current row
printf("The max element of row %d is %d\n", i, ans); // Print the result
}

return 0; // Exit the program


}

1.(b) Write a program to find the nth term in the Fibonacci series using recursion.
#include<stdio.h>

// Recursive function to calculate the nth Fibonacci number


// Parameters: n (the position in the Fibonacci sequence)
int fib(int n) {
if (n == 0) { // Base case: Fibonacci(0) is 0
return 0;
}
else if (n == 1) { // Base case: Fibonacci(1) is 1
return 1;
}
else { // Recursive case: Fibonacci(n) = Fibonacci(n-1) + Fibonacci(n-2)
return fib(n - 1) + fib(n - 2);
}
}

int main() {
int n; // Variable to store the number of terms

// Prompt user to enter the number of terms in the Fibonacci sequence


printf("Enter the number of terms:\n");
scanf("%d", &n);

// Generate and print the Fibonacci sequence up to the nth term


for (int i = 0; i < n; i++) {
int ans = fib(i); // Calculate the ith Fibonacci number using the fib
function
printf("%d ", ans); // Print the ith Fibonacci number
}

return 0; // Exit the program


}

2. Write a program to design, Develop and Implement a menu- driven program in C for

the following operations on STACK of integers (Array implementation of the stack


with maximum size of N).
i) Push an element on to stack.
ii) Pop an element from the stack.
iii) Check Overflow and Underflow situations on the stack.
iv) Display the contents of stack.
v) Exit.
Support the program with appropriate functions for each of the above operations.

#include<stdio.h>
#include<stdlib.h>
#define Max 5 // Define the maximum size of the stack
int stack[Max]; // Array to represent the stack
int top = -1; // Variable to keep track of the top of the stack

// Function to push an element onto the stack


void push(int element) {
if (top == Max - 1) { // Check if the stack is full
printf("Stack overflow\n"); // Print an error message if the stack is full
} else {
stack[++top] = element; // Increment the top and insert the element
printf("The pushed element is %d\n", element); // Confirm the pushed element
}
}

// Function to pop an element from the stack


void pop() {
if (top == -1) { // Check if the stack is empty
printf("Stack underflow\n"); // Print an error message if the stack is empty
} else {
printf("The popped element is %d\n", stack[top--]); // Print and remove the
top element
}
}

// Function to display the elements of the stack


void display() {
if (top == -1) { // Check if the stack is empty
printf("Stack is empty\n"); // Print a message if the stack is empty
} else {
printf("The stack elements are:\n");
for (int i = top; i >= 0; i--) { // Loop to print all elements from top to
bottom
printf("%d ", stack[i]);
}
printf("\n");
}
}

int main() {
int element, ch; // Variables for the element and user's choice

while (1) { // Infinite loop to continuously display menu options


printf("Press 1 to push element\n");
printf("Press 2 to pop element\n");
printf("Press 3 to display elements\n");
printf("Press 4 to exit\n");
printf("Choose a number:\n");
scanf("%d", &ch); // Read the user's choice

switch (ch) {
case 1: // Push operation
printf("Enter the value:\n");
scanf("%d", &element);
push(element);
break;

case 2: // Pop operation


pop();
break;

case 3: // Display stack elements


display();
break;

case 4: // Exit the program


printf("Exiting the code\n");
exit(0);

default: // Invalid input


printf("Invalid input\n");
break;
}
}
return 0;
}

3. (a) Write a C program to read and display the Time in specified format. Create a

structure called TIME with hour (int), minute(int), second(int) and next (self
Referencing pointer) as its members. Dynamically create two variables of structure
TIME and link the first variable to the second one and display it. Write a Display
function that takes address of first TIME variable and displays both times in the
Format h: m: s
#include <stdio.h>
#include<stdlib.h>

// Define a structure to represent time


struct time
{
int h, m, s; // Hours, minutes, seconds
struct time *next; // Pointer to the next time node
};

int main() {

struct time *t1, *t2; // Declare pointers for two time nodes
// Allocate memory for the first time node
t1 = malloc(sizeof(struct time));
printf("Enter the hour, minute, and second for time 1\n");
// Input values for the first time node
scanf("%d%d%d", &t1->h, &t1->m, &t1->s);
// Allocate memory for the second time node
t2 = malloc(sizeof(struct time));
printf("Enter the hour, minute, and second for time 2\n");
// Input values for the second time node
scanf("%d%d%d", &t2->h, &t2->m, &t2->s);
// Link the first time node to the second
t1->next = t2;
// Call the display function to print the times
display(t1);
return 0;
}

// Function to display times from the linked list


void display(struct time *t) {
struct time *temp = t; // Temporary pointer for traversal
printf("The time is:\n");
// Print the first time node's values
printf("%d:%d:%d\n", temp->h, temp->m, temp->s);
temp = temp->next; // Move to the next node
// Print the second time node's values
printf("%d:%d:%d\n", temp->h, temp->m, temp->s);
}

3. (b) Write a C program to check whether a given string is a palindrome or not by

using stack.
#include <stdio.h>
#include <string.h>
#include <stdbool.h>

#define Max 20

char stack[Max];
int top = -1;

// Push function
void push(char item) {
if (top == Max - 1) {
printf("Stack overflow\n");
return;
}
stack[++top] = item;
}

// Pop function
char pop() {
if (top == -1) {
printf("Stack underflow\n");
return '\0';
}
return stack[top--];
}

// Function to check if a string is a palindrome


bool ispalindrome(const char *str) {
int len = strlen(str);
if (len == 0) return true; // Empty string is a palindrome

int mid = len / 2;

// Push first half to stack


for (int i = 0; i < mid; i++) {
push(str[i]);
}

// Start checking from the middle


int start = (len % 2 == 0) ? mid : mid + 1;
for (int i = start; i < len; i++) {
char ch = pop();
if (ch != str[i]) {
return false; // Not a palindrome
}
}
return true; // Palindrome
}

int main() {
char input[Max];
printf("Enter a string: ");
scanf("%s", input); // Limit input to prevent overflow

if (ispalindrome(input)) {
printf("The given string is a palindrome.\n");
} else {
printf("The given string is not a palindrome.\n");
}

return 0;
}

4. Write a C program to read and display the student details. Define a structure 'Student' with fields name
(string) , usn (int), marks of 3 subjects (int) and Average (float) in it. Store the details of n students in an array
of structure 'Student'. Display the details of all students in the descending order their total marks.
#include <stdio.h>
// Define the structure for student
struct student {
char name[20]; // Student name
int usn; // University serial number
int m1, m2, m3; // Marks for three subjects
float avg; // Average of marks
};

int main() {
struct student s[20]; // Array to store student details
int n, total = 0; // Number of students and a variable to calculate total
marks

// Input the number of students


printf("Enter the number of students: ");
scanf("%d", &n);

// Input details for each student


printf("Enter student details:\n");
for (int i = 0; i < n; i++) {
printf("\nStudent %d:\n", i + 1);

printf("Enter the name: ");


scanf("%s", s[i].name);

printf("Enter the USN: ");


scanf("%d", &s[i].usn);

printf("Enter the marks of 3 subjects: ");


scanf("%d %d %d", &s[i].m1, &s[i].m2, &s[i].m3);

// Calculate the average


total = s[i].m1 + s[i].m2 + s[i].m3;
s[i].avg = total / 3.0;
}

// Sort the students in descending order of their average marks


for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (s[i].avg < s[j].avg) {
// Swap the students
struct student temp = s[i];
s[i] = s[j];
s[j] = temp;
}
}
}

// Print the student details in descending order of average marks


printf("\nThe student details in descending order of average marks are:\n");
for (int i = 0; i < n; i++) {
printf("\nStudent %d:\n", i + 1);
printf("Name: %s\n", s[i].name);
printf("USN: %d\n", s[i].usn);
printf("Average Marks: %.2f\n", s[i].avg);
}

return 0;
}

5. Write a C program using dynamic variables and pointers, to construct singly linked
list. The operations to be supported are:
(i)
Insert at the front of a list.
(ii)
Deleting a node based on specified value.
(iii)
Displaying all the nodes in the list.
#include <stdio.h>
#include <stdlib.h>

// Define the structure of a node in the linked list


struct node {
int data; // Data part of the node
struct node *next; // Pointer to the next node
} *first = NULL, *temp = NULL, *temp1, *nn;

// Function to create a new node with a given value


void create(int val) {
nn = (struct node*)malloc(sizeof(struct node)); // Allocate memory for a new node
nn->data = val; // Set the data of the new node
nn->next = NULL; // Initialize the next pointer to NULL
}

// Function to insert a new node at the beginning of the linked list


void insert(int val) {
create(val); // Create a new node with the given value
if (first == NULL) { // If the linked list is empty
first = nn; // Set the new node as the first node
} else {
nn->next = first; // Point the new node's next to the current first node
first = nn; // Update the first node to the new node
}
}

// Function to delete a node with a specific key (value) from the linked list
void delete(int key) {
temp = first; // Start with the first node
if (temp == NULL) { // If the linked list is empty
printf("empty ll");
return;
}

// Traverse the linked list to find the node with the given key
while (temp->data != key) {
temp1 = temp; // Keep track of the previous node
temp = temp->next; // Move to the next node
if (temp == NULL) { // If the key is not found
printf("Key not found\n");
return;
}
}

// If the node to be deleted is the first node


if (temp == first) {
first = temp->next; // Update the first node to the next node
free(temp); // Free the memory of the deleted node
return;
}

// For all other nodes, bypass the node to be deleted


temp1->next = temp->next; // Update the previous node's next pointer
printf("The deleted node is %d\n", temp->data); // Print the deleted node's value
free(temp); // Free the memory of the deleted node
}

// Function to display the linked list


void display() {
temp = first; // Start with the first node
if (temp == NULL) { // If the linked list is empty
printf("empty ll");
return;
}

printf("The nodes from beginning:\n");


while (temp != NULL) { // Traverse the linked list
printf("%d ", temp->data); // Print each node's data
temp = temp->next; // Move to the next node
}
printf("\n");
}

int main() {
int ch, val, key;

// Menu-driven program for linked list operations


while (1) {
printf("\n1. Insert");
printf("\n2. Delete");
printf("\n3. Display");
printf("\n4. Exit");

printf("\nEnter the choice:\n");


scanf("%d", &ch); // Read the user's choice

switch (ch) {
case 1:
printf("Enter the value to insert:\n");
scanf("%d", &val); // Read the value to be inserted
insert(val); // Call the insert function
break;
case 2:
printf("Enter the value to delete:\n");
scanf("%d", &key); // Read the value to be deleted
delete(key); // Call the delete function
break;
case 3:
display(); // Call the display function
break;
case 4:
exit(0); // Exit the program
default:
printf("Invalid choice\n"); // Handle invalid input
break;
}
}
return 0;
}

6. Write a C program using dynamic variables and pointers, to construct singly linked
list. The operations to be supported are:
(i)
Insert at 3 rd position in the list.
(ii)
Searching a node based on specified value.
(iii)
Displaying all the nodes in the list.
#include <stdio.h>
#include <stdlib.h>

// Define the structure of a node in the linked list


struct node {
int data; // Data part of the node
struct node *next; // Pointer to the next node
} *first = NULL, *last = NULL, *temp = NULL, *temp1, *nn;

int count = 0; // Counter to track the number of nodes in the linked list

// Function to create a new node with a given value


void create(int val) {
nn = (struct node *)malloc(sizeof(struct node)); // Allocate memory for a new
node
nn->data = val; // Set the data of the new node
nn->next = NULL; // Initialize the next pointer to NULL
count++; // Increment the node count
}

// Function to insert a new node into the linked list


void insert(int val) {
create(val); // Create a new node with the given value

if (first == NULL) { // If the linked list is empty


printf("Linked list is empty, inserting at first\n");
first = nn; // Set the new node as the first node
last = first; // Update the last node to the new node
} else if (count < 3) { // If the linked list has less than 3 nodes
printf("Linked list has less than 3 nodes, inserting at the end\n");
last->next = nn; // Add the new node at the end
last = nn; // Update the last node to the new node
} else { // If the linked list has 3 or more nodes
temp1 = first; // Start from the first node
for (int i = 0; i < 1; i++) { // Traverse to the 2nd node (position before
the 3rd)
temp1 = temp1->next;
}
nn->next = temp1->next; // Insert the new node at the 3rd position
temp1->next = nn;
}
}

// Function to find the position of a node with a specific value


void position(int key) {
temp = first; // Start with the first node
int pos = 1; // Position counter

if (temp == NULL) { // If the linked list is empty


printf("Linked list is empty\n");
return;
}

while (temp != NULL) { // Traverse the linked list


if (temp->data == key) { // If the node with the given value is found
printf("The node %d is found at position %d\n", temp->data, pos);
return;
}
temp = temp->next; // Move to the next node
pos++; // Increment the position counter
}
printf("The node with value %d is not in the list\n", key); // If the value is
not found
}

// Function to display the linked list


void display() {
temp = first; // Start with the first node

if (temp == NULL) { // If the linked list is empty


printf("Linked list is empty\n");
return;
}

printf("The nodes from beginning:\n");


while (temp != NULL) { // Traverse the linked list
printf("%d ", temp->data); // Print each node's data
temp = temp->next; // Move to the next node
}
printf("\n");
}

int main() {
int ch, val, key;

// Menu-driven program for linked list operations


while (1) {
printf("\n1. Insert");
printf("\n2. Find Position");
printf("\n3. Display");
printf("\n4. Exit\n");

printf("Enter your choice: ");


scanf("%d", &ch); // Read the user's choice

switch (ch) {
case 1:
printf("Enter the value to insert: ");
scanf("%d", &val); // Read the value to be inserted
insert(val); // Call the insert function
break;
case 2:
printf("Enter the value to find position: ");
scanf("%d", &key); // Read the value to find
position(key); // Call the position function
break;
case 3:
display(); // Call the display function
break;
case 4:
exit(0); // Exit the program
default:
printf("Invalid choice\n"); // Handle invalid input
break;
}
}
return 0;
}

7. Write a C program to reverse a linked list elements.


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

// Global variable to keep track of the number of nodes


int count = 0;

// Define the structure for a node in the linked list


struct node {
int data; // To store the data of the node
struct node *next; // Pointer to the next node in the list
} *first = NULL, *temp = NULL; // Global pointers for the first node and temporary
node

// Function to create a new node


void create() {
// Dynamically allocate memory for a new node
temp = (struct node*)malloc(sizeof(struct node));
if (temp == NULL) { // Check if memory allocation failed
printf("\nMemory allocation failed.\n");
exit(1);
}

// Input data for the node


printf("\n Enter the data: ");
scanf("%d", &temp->data);
temp->next = NULL; // Initialize the next pointer to NULL
}

// Function to insert a node at the front of the linked list


void insertAtFront() {
if (first == NULL) { // If the list is empty
create(); // Create the first node
first = temp; // Set the first pointer to the new node
} else {
create(); // Create a new node
temp->next = first; // Point the new node to the current first node
first = temp; // Update the first pointer to the new node
}
count++; // Increment the count of nodes
}

// Function to display the elements of the linked list


void displayList() {
struct node *current = first; // Start from the first node
if (current == NULL) { // Check if the list is empty
printf("\nThe list is empty.\n");
return;
}

printf("\nThe elements of the list are:");


while (current != NULL) { // Traverse the list until the end
printf(" %d", current->data); // Print the data of the current node
current = current->next; // Move to the next node
}
printf("\n");
}

// Function to reverse the linked list


struct node* reverseList(struct node* first) {
struct node *prev = NULL; // Pointer to the previous node
struct node *current = first; // Pointer to the current node
struct node *next = NULL; // Pointer to the next node

// Iterate through the list


while (current != NULL) {
next = current->next; // Save the next node
current->next = prev; // Reverse the current node's pointer
prev = current; // Move the previous pointer forward
current = next; // Move the current pointer forward
}

// The previous pointer is now the new head of the reversed list
return prev;
}

// Main function
int main() {
int n, i;

// Input the number of nodes to create


printf("\n Enter the number of nodes: ");
scanf("%d", &n);

// Insert nodes at the front of the list


for (i = 0; i < n; i++) {
insertAtFront();
}

// Display the original list


printf("\n Original List: ");
displayList();

// Reverse the list and update the first pointer


first = reverseList(first);

// Display the reversed list


printf("\n Reversed List: ");
displayList();

return 0; // Exit the program


}

8. Write a C program to support the following operations on doubly linked list where
each node consists of integers.
(i)
Create a doubly linked list by adding each node at the front.
(ii)
Insert a new node to the left of the node whose key value is read as an input.
(iii)
Display all the contents of the list.
#include <stdio.h>
#include <stdlib.h>

// Define the structure of a node in the doubly linked list


struct node {
int data; // Data part of the node
struct node *next; // Pointer to the next node
struct node *prev; // Pointer to the previous node
} *first = NULL, *last = NULL, *nn, *ptr;

int count = 0; // Counter to track the number of nodes in the linked list

// Function to create a new node with a given value


void create(int val) {
nn = (struct node *)malloc(sizeof(struct node)); // Allocate memory for a new
node
nn->data = val; // Set the data of the new node
nn->next = NULL; // Initialize the next pointer to NULL
nn->prev = NULL; // Initialize the previous pointer to NULL
}
// Function to insert a new node at the beginning of the linked list
void insert(int val) {
create(val); // Create a new node with the given value

if (first == NULL) { // If the linked list is empty


first = nn; // Set the new node as the first node
last = first; // Update the last node to the new node
} else { // If the linked list has nodes
nn->next = first; // Link the new node to the current first node
first->prev = nn; // Update the previous pointer of the current first node
first = nn; // Update the first pointer to the new node
}
}

// Function to insert a new node to the left of a node with a given key
void insert_at_left(int key) {
int val;
ptr = first; // Start traversal from the first node

while (ptr != NULL) { // Traverse the linked list


if (ptr->data == key) { // Check if the current node's data matches the key
printf("Enter the value to insert: ");
scanf("%d", &val); // Read the value to be inserted
create(val); // Create a new node with the given value

if (ptr == first) { // If the key is found in the first node


nn->next = first; // Link the new node to the current first node
first->prev = nn; // Update the previous pointer of the current first
node
first = nn; // Update the first pointer to the new node
} else { // If the key is found in any other node
nn->next = ptr; // Link the new node to the current node
nn->prev = ptr->prev; // Link the new node to the previous node
ptr->prev->next = nn; // Update the next pointer of the previous node
ptr->prev = nn; // Update the previous pointer of the current node
}
return;
}
ptr = ptr->next; // Move to the next node
}
printf("Key not found\n"); // Print message if the key is not found
}

// Function to display the linked list from the beginning


void display() {
struct node *temp = first; // Start with the first node

if (temp == NULL) { // If the linked list is empty


printf("Linked list is empty\n");
return;
}

printf("The nodes from beginning:\n");


while (temp != NULL) { // Traverse the linked list
printf("%d ", temp->data); // Print each node's data
temp = temp->next; // Move to the next node
}
printf("\n");
}

int main() {
int ch, val, key;

// Menu-driven program for linked list operations


while (1) {
printf("\n1. Insert");
printf("\n2. Insert at left of a key");
printf("\n3. Display");
printf("\n4. Exit\n");

printf("Enter your choice: ");


scanf("%d", &ch); // Read the user's choice

switch (ch) {
case 1:
printf("Enter the value to insert: ");
scanf("%d", &val); // Read the value to be inserted
insert(val); // Call the insert function
break;
case 2:
printf("Enter the key to insert left of: ");
scanf("%d", &key); // Read the key to find
insert_at_left(key); // Call the insert_at_left function
break;
case 3:
display(); // Call the display function
break;
case 4:
exit(0); // Exit the program
default:
printf("Invalid choice\n"); // Handle invalid input
break;
}
}
return 0;
}

10. Write a C program to convert an expression given in “infix” form to “postfix” form
using stack concept.
#include <ctype.h> // For isalnum() function
#include <stdio.h>

#define SIZE 50 // Define the size of the stack

char S[SIZE]; // Stack to hold operators and parentheses


int top = -1; // Initialize the stack's top pointer to -1 (empty stack)

// Function to push an element onto the stack


void push(char elem) {
S[++top] = elem; // Increment the top pointer and store the element
}

// Function to pop an element from the stack


char pop() {
return (S[top--]); // Return the top element and decrement the top pointer
}

// Function to determine the precedence of operators


int pr(char elem) {
switch (elem) {
case '(':
return 1; // Parentheses have the lowest precedence
case '+':
case '-':
return 2; // Addition and subtraction have lower precedence
case '*':
case '/':
case '%':
return 3; // Multiplication, division, and modulus have higher precedence
case '^':
return 4; // Exponentiation has the highest precedence
}
return 0; // Default case (should not occur)
}

// Main function to convert an infix expression to postfix


void main() {
char infix[50], pofx[50], ch, elem; // Arrays for infix and postfix expressions
int i = 0, k = 0; // Counters for traversing infix and building postfix
expressions

printf("\n Enter the Infix Expression: ");


scanf("%s", infix); // Read the infix expression

push('('); // Push an opening parenthesis onto the stack to indicate the start
while ((ch = infix[i++]) != '\0') { // Traverse the infix expression
if (ch == '(') {
push(ch); // Push an opening parenthesis onto the stack
} else if (isalnum(ch)) {
pofx[k++] = ch; // If the character is an operand, add it to the postfix
expression
} else if (ch == ')') {
// If a closing parenthesis is encountered
while (S[top] != '(') {
pofx[k++] = pop(); // Pop and add operators to the postfix expression
until '(' is found
}
elem = pop(); // Remove the '(' from the stack
} else {
// If the character is an operator
while (pr(S[top]) >= pr(ch)) {
// Pop operators from the stack with precedence >= current operator
pofx[k++] = pop();
}
push(ch); // Push the current operator onto the stack
}
}

// Pop any remaining operators from the stack and add to postfix expression
while (S[top] != '(') {
pofx[k++] = pop();
}
pofx[k] = '\0'; // Null-terminate the postfix expression

// Display the results


printf("\nGiven Infix Expression: %s", infix);
printf("\nPostfix Expression: %s", pofx);
}

11. Write a C program to simulate the working of a queues using an array provide and
implement the following operations:
i) Insert
ii) Delete
iii) Display
Assume that the size of the queue is 5.
#include<stdio.h>
#include<stdlib.h>

#define MAX 5 // Define the maximum size of the queue


int queue[MAX], front=-1, rear=-1; // Declare the queue and initialize front and rear
pointers

// Function prototypes
void insert(int); // Function to insert an element into the queue
void delete(); // Function to delete an element from the queue
void display(); // Function to display the elements of the queue

int main()
{
int choice, num;
while(1) // Infinite loop to display menu and take user input
{
printf(" \n1.INSERT\n2.DELETE \n3.DISPLAY \n4.EXIT"); // Display menu options
printf("\nEnter the Choice:");
scanf("%d", &choice); // Take user input for the choice

switch(choice)
{
case 1:
printf("Enter value to insert: ");
scanf("%d", &num); // Take input value for insertion
insert(num); // Call the insert function
break;
case 2:
delete(); // Call the delete function
break;
case 3:
display(); // Call the display function
break;
case 4:
printf("\n EXIT POINT\n"); // Exit message
exit(0); // Exit the program
default:
printf ("\nEnter Valid Choice\n"); // Handle invalid choice
}
}
return 0;
}

// Function to insert an element into the queue


void insert(int num)
{
// Check if the queue is full (overflow condition)
if(rear == MAX - 1)
{
printf("\n OVERFLOW"); // Print overflow message
return; // Exit the function if queue is full
}
// If the queue is empty (both front and rear are -1), set both to 0
else if(front == -1 && rear == -1)
{
front = rear = 0; // Set front and rear to 0, indicating an empty queue
}
else
{
rear++; // Increment rear pointer to add element at the end
}
queue[rear] = num; // Insert the new element at the rear of the queue
}

// Function to delete an element from the queue


void delete()
{
int val;
// Check if the queue is empty (underflow condition)
if(front == -1 || front > rear)
{
printf("\n UNDERFLOW"); // Print underflow message
}
else
{
val = queue[front]; // Get the element at the front of the queue
printf("Deleted Item: %d", val); // Print the deleted item
front++; // Increment front pointer to remove the element
// If the queue becomes empty after deletion, reset front and rear to -1
if(front > rear)
{
front = rear = -1; // Reset queue to empty state
}
}
}

// Function to display all elements in the queue


void display()
{
int i;
// Check if the queue is empty
if(front == -1 || front > rear)
{
printf("\n QUEUE EMPTY"); // Print empty message if queue is empty
}
else
{
printf("Queue data:\n");
// Iterate from front to rear and print each element
for(i = front; i <= rear; i++)
{
printf("\t %d", queue[i]); // Print each element in the queue
}
}
}
12. Write a C program to implement a circular queue using linked lists.
#include <stdio.h>
#include <stdlib.h>

// Define the structure of a node


typedef struct node
{
int num; // Data part of the node (stores integer value)
struct node *next; // Pointer to the next node in the circular queue
} NODE;

// Function declarations
void insert_rear(int); // Insert a node at the rear of the queue
void delete_front(); // Delete a node from the front of the queue
void display(); // Display all nodes in the queue

// Global pointers to the front and rear of the queue


NODE *front = NULL, *rear = NULL;

void main()
{
int num, ch;
while(1) // Infinite loop for user to choose operations
{
printf("\nEnter your choice\n");
printf("1. Insert at rear\n");
printf("2. Delete at front\n");
printf("3. Display\n");
printf("4. Exit\n");
scanf("%d", &ch); // Take user input for menu choice

switch(ch) // Switch-case for menu operations


{
case 1:
printf("Enter data to insert: ");
scanf("%d", &num); // Take input for the node to insert
insert_rear(num); // Call function to insert at rear
break;

case 2:
delete_front(); // Call function to delete the front node
break;

case 3:
display(); // Call function to display the queue
break;

case 4:
exit(0); // Exit the program
}
}
}

// Function to insert a new node at the rear of the queue


void insert_rear(int n)
{
NODE *new_node;
// Allocate memory for a new node
new_node = (NODE *)malloc(sizeof(struct node));
new_node->num = n; // Assign the given value to the new node
new_node->next = front; // Point the new node's next to the front node (circular
link)

// Case when the queue is empty (both front and rear are NULL)
if ((front == NULL) && (rear == NULL))
{
front = rear = new_node; // Set both front and rear to the new node
front->next = front; // Circular link: the node points to itself
}
else
{
// Case when the queue already has nodes
rear->next = new_node; // Link the current rear node to the new node
new_node->next = front; // Circular link: new node points to the front
rear = new_node; // Move rear pointer to the newly added node
}
return;
}

// Function to delete a node from the front of the queue


void delete_front()
{
NODE *ptr;

// Case when the queue is empty (both front and rear are NULL)
if ((front == NULL) && (rear == NULL))
{
printf("Queue Empty\n"); // Print message and return if the queue is empty
}
// Case when there is only one node in the queue (front points to rear)
else if (front->next == front)
{
printf("Item deleted: %d\n", front->num); // Print the value of the node
being deleted
free(front); // Free the memory occupied by the front node
front = rear = NULL; // Set both front and rear to NULL (queue is empty)
}
else
{
// Case when there are multiple nodes in the queue
ptr = front; // Save the front node to a temporary pointer
front = front->next; // Move the front pointer to the next node
rear->next = front; // Update the rear's next pointer to the new front
(maintain circular link)
printf("Item deleted: %d\n", ptr->num); // Print the value of the node being
deleted
free(ptr); // Free the memory occupied by the old front node
}
return;
}

// Function to display the elements of the queue


void display()
{
NODE *ptr;
ptr = front;

// Case when the queue is empty (front is NULL)


if (ptr == NULL)
printf("Queue empty\n"); // Print a message indicating the queue is empty
else
{
printf("The Queue data are: \n");
// Traverse the queue from front to rear, displaying each element
do
{
printf("%d ", ptr->num); // Print the data of the current node
ptr = ptr->next; // Move to the next node
}
while (ptr != front); // Continue until we circle back to the front
}
return;
}

9. Write a C program to support the following operations on doubly linked list where
each node consists of integers.
(i)
Delete the node of a given data, if it is found, otherwise display appropriate
message.
(ii)
Searching a node based on specified value.
(iii)
Display all the contents of the list.

#include <stdio.h>
#include <stdlib.h>
// Define the structure of a node in the doubly linked list
struct node {
int data; // Data part of the node
struct node *next; // Pointer to the next node
struct node *prev; // Pointer to the previous node
} *first = NULL, *last = NULL, *temp = NULL, *temp1, *nn, *ptr;

// Function to create a new node with a given value


void create(int val) {
nn = (struct node *)malloc(sizeof(struct node)); // Allocate memory for a new
node
nn->data = val; // Set the data of the new node
nn->next = NULL; // Initialize the next pointer to NULL
nn->prev = NULL; // Initialize the prev pointer to NULL
}

// Function to insert a new node at the beginning of the linked list


void insert(int val) {
create(val); // Create a new node with the given value

if (first == NULL) { // If the linked list is empty


first = nn; // Set the new node as the first node
last = first; // Update the last node to the new node
} else { // If the linked list is not empty
nn->next = first; // Point the new node's next to the current first node
first->prev = nn; // Point the current first node's prev to the new node
first = nn; // Update the first node to the new node
}
}

// Function to find the position of a node with a specific value


void position(int key) {
temp = first; // Start with the first node
int pos = 1; // Position counter

if (temp == NULL) { // If the linked list is empty


printf("Linked list is empty\n");
return;
}

while (temp != NULL) { // Traverse the linked list


if (temp->data == key) { // If the node with the given value is found
printf("The node %d is found at position %d\n", temp->data, pos);
return;
}
temp = temp->next; // Move to the next node
pos++; // Increment the position counter
}
printf("The node with value %d is not in the list\n", key); // If the value is
not found
}

// Function to delete a node with a specific value


void delete(int elem) {
if (first == NULL) { // If the linked list is empty
printf("Linked list is empty\n");
return;
}

ptr = first; // Start with the first node


while (ptr != NULL) { // Traverse the linked list
if (ptr->data == elem) { // If the node with the given value is found
if (ptr == first && ptr == last) { // If the node is the only node in the
list
first = NULL; // Update first to NULL
last = NULL; // Update last to NULL
} else if (ptr == first) { // If the node is the first node
first = ptr->next; // Update first to the next node
first->prev = NULL; // Update the new first node's prev to NULL
} else if (ptr == last) { // If the node is the last node
last = ptr->prev; // Update last to the previous node
last->next = NULL; // Update the new last node's next to NULL
} else { // If the node is in the middle
ptr->next->prev = ptr->prev; // Update the next node's prev pointer
ptr->prev->next = ptr->next; // Update the previous node's next
pointer
}

printf("The deleted node is %d\n", ptr->data); // Print the deleted


node's value
free(ptr); // Free the memory allocated for the node
return;
}
ptr = ptr->next; // Move to the next node
}
printf("The node with value %d was not found\n", elem); // If the value is not
found
}

// Function to display the linked list


void display() {
temp = first; // Start with the first node

if (temp == NULL) { // If the linked list is empty


printf("Linked list is empty\n");
return;
}
printf("The nodes from beginning:\n");
while (temp != NULL) { // Traverse the linked list
printf("%d ", temp->data); // Print each node's data
temp = temp->next; // Move to the next node
}
printf("\n");
}

// Main function: menu-driven program for linked list operations


int main() {
int ch, val, key, elem;

while (1) {
// Display menu options
printf("\n1. Insert");
printf("\n2. Find Position");
printf("\n3. Delete");
printf("\n4. Display");
printf("\n5. Exit\n");

printf("Enter your choice: ");


scanf("%d", &ch); // Read the user's choice

switch (ch) {
case 1:
printf("Enter the value to insert: ");
scanf("%d", &val); // Read the value to be inserted
insert(val); // Call the insert function
break;
case 2:
printf("Enter the value to find position: ");
scanf("%d", &key); // Read the value to find
position(key); // Call the position function
break;
case 3:
printf("Enter the value to delete: ");
scanf("%d", &elem); // Read the value to delete
delete(elem); // Call the delete function
break;
case 4:
display(); // Call the display function
break;
case 5:
exit(0); // Exit the program
default:
printf("Invalid choice\n"); // Handle invalid input
break;
}
}
return 0;
}

13.Write a C program to construct a binary search tree of integers and also display the elements in the tree using
Inorder, Preorder and Postorder traversals.

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

// Define the structure of a node in the binary search tree


typedef struct Node {
int data; // Stores the integer value of the node
struct Node* left; // Pointer to the left child (smaller values)
struct Node* right; // Pointer to the right child (larger values)
} Node;

// Function to create a new node


Node* createNode(int data) {
Node* newNode = (Node*)malloc(sizeof(Node)); // Allocate memory for the new node
newNode->data = data; // Set the data for the new node
newNode->left = NULL; // Initialize left child as NULL
newNode->right = NULL; // Initialize right child as NULL
return newNode; // Return the newly created node
}

// Function to insert a node into the binary search tree (BST)


Node* insert(Node* root, int data) {
if (root == NULL) { // If the tree is empty, create a new
root node
return createNode(data);
}
if (data < root->data) { // If the data is smaller, insert
into the left subtree
root->left = insert(root->left, data);
} else if (data > root->data) { // If the data is larger, insert into
the right subtree
root->right = insert(root->right, data);
}
return root; // Return the root node after
insertion
}

// Function for Inorder traversal (Left, Root, Right)


void inorder(Node* root) {
if (root != NULL) {
inorder(root->left); // Recursively visit the left subtree
printf("%d ", root->data); // Print the value of the current
node
inorder(root->right); // Recursively visit the right
subtree
}
}

// Function for Preorder traversal (Root, Left, Right)


void preorder(Node* root) {
if (root != NULL) {
printf("%d ", root->data); // Print the value of the current
node
preorder(root->left); // Recursively visit the left subtree
preorder(root->right); // Recursively visit the right
subtree
}
}

// Function for Postorder traversal (Left, Right, Root)


void postorder(Node* root) {
if (root != NULL) {
postorder(root->left); // Recursively visit the left subtree
postorder(root->right); // Recursively visit the right
subtree
printf("%d ", root->data); // Print the value of the current
node
}
}

// Main function to demonstrate BST operations


int main() {
Node* root = NULL; // Initialize the root of the BST as
NULL
int choice, value; // Variables for user input

// Display the menu for BST operations


printf("Binary Search Tree Operations:\n");
printf("1. Insert\n");
printf("2. Display Inorder\n");
printf("3. Display Preorder\n");
printf("4. Display Postorder\n");
printf("5. Exit\n");

while (1) { // Infinite loop to process user


choices
printf("\nEnter your choice: "); // Prompt for user input
scanf("%d", &choice); // Read the user's choice

switch (choice) { // Perform the action based on the


user's choice
case 1: // Case for inserting a value into
the BST
printf("Enter value to insert: ");
scanf("%d", &value); // Read the value to insert
root = insert(root, value); // Insert the value into the BST
break;
case 2: // Case for displaying Inorder
traversal
printf("Inorder Traversal: ");
inorder(root); // Perform Inorder traversal
printf("\n");
break;
case 3: // Case for displaying Preorder
traversal
printf("Preorder Traversal: ");
preorder(root); // Perform Preorder traversal
printf("\n");
break;
case 4: // Case for displaying Postorder
traversal
printf("Postorder Traversal: ");
postorder(root); // Perform Postorder traversal
printf("\n");
break;
case 5: // Case for exiting the program
printf("Exiting program.\n");
return 0; // Exit the program
default: // Handle invalid choices
printf("Invalid choice. Please try again.\n");
}
}
return 0; // End of main function
}

14.a) Write a C program to find the number of leaf nodes in a BST


b) Write a C program to print all root to leaf paths of a BST.

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

// Define the structure of a node in the binary search tree


typedef struct Node {
int data; // Holds the value of the node
struct Node* left; // Pointer to the left child (smaller values)
struct Node* right; // Pointer to the right child (larger values)
} Node;

// Function to create a new node


Node* createNode(int data) {
Node* newNode = (Node*)malloc(sizeof(Node)); // Allocate memory for the new node
newNode->data = data; // Set the data value for the new
node
newNode->left = NULL; // Initialize the left child as NULL
newNode->right = NULL; // Initialize the right child as NULL
return newNode; // Return the newly created node
}

// Function to insert a node into the binary search tree (BST)


Node* insert(Node* root, int data) {
if (root == NULL) { // If the tree is empty, create a new
root node
return createNode(data);
}
if (data < root->data) { // If the data is smaller, insert
into the left subtree
root->left = insert(root->left, data);
} else if (data > root->data) { // If the data is larger, insert into
the right subtree
root->right = insert(root->right, data);
}
return root; // Return the root node after
insertion
}

// Function to count the number of leaf nodes in the BST


int countLeafNodes(Node* root) {
if (root == NULL) {
return 0; // Base case: If the tree is empty, there are no leaf nodes
}
if (root->left == NULL && root->right == NULL) {
return 1; // Base case: A node with no children is a leaf node
}
// Recursively count leaf nodes in the left and right subtrees
return countLeafNodes(root->left) + countLeafNodes(root->right);
}

// Helper function to print a single root-to-leaf path


void printPath(int path[], int pathLength) {
for (int i = 0; i < pathLength; i++) { // Loop through the elements in the
path array
printf("%d ", path[i]); // Print each element of the path
}
printf("\n"); // Print a newline to separate paths
}
// Function to find and print all root-to-leaf paths
void printRootToLeafPaths(Node* root, int path[], int pathLength) {
if (root == NULL) {
return; // Base case: If the current node is NULL, do nothing and return
}

// Add the current node's data to the path array


path[pathLength] = root->data;
pathLength++; // Increment the path length

// If the current node is a leaf node (no left or right children)


if (root->left == NULL && root->right == NULL) {
printPath(path, pathLength); // Print the path from root to this
leaf
} else {
// Otherwise, recursively find paths in the left and right subtrees
printRootToLeafPaths(root->left, path, pathLength);
printRootToLeafPaths(root->right, path, pathLength);
}
}

// Main function to demonstrate the BST operations


int main() {
Node* root = NULL; // Initialize the root of the BST as
NULL
int choice, value; // Variables for user input
int path[100]; // Array to store the current path
(max size 100; adjust if needed)

// Display menu for BST operations


printf("Binary Search Tree Operations:\n");
printf("1. Insert\n"); // Option to insert a value into the
BST
printf("2. Count Leaf Nodes\n"); // Option to count the number of leaf
nodes
printf("3. Print All Root-to-Leaf Paths\n"); // Option to display all root-to-
leaf paths
printf("4. Exit\n"); // Option to exit the program

// Infinite loop to handle user input and perform operations


while (1) {
printf("\nEnter your choice: "); // Prompt user to enter a choice
scanf("%d", &choice); // Read the user's choice

switch (choice) { // Handle user's choice using a


switch-case statement
case 1: // Insert a value into the BST
printf("Enter value to insert: ");
scanf("%d", &value); // Read the value to be inserted
root = insert(root, value); // Insert the value into the BST
break;
case 2: // Count the number of leaf nodes
printf("Number of Leaf Nodes: %d\n", countLeafNodes(root));
break;
case 3: // Print all root-to-leaf paths
printf("Root-to-Leaf Paths:\n");
printRootToLeafPaths(root, path, 0); // Start the recursive path
printing function
break;
case 4: // Exit the program
printf("Exiting program.\n");
return 0; // Exit the program
default: // Handle invalid input
printf("Invalid choice. Please try again.\n");
}
}
return 0; // End of the main function
}

You might also like