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

Data Structures Laboratory

Uploaded by

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

Data Structures Laboratory

Uploaded by

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

Visvesvaraya Technological University (VTU)

Data Structures Laboratory


BSCSL305

Aug 15, 2024

RAJIV GANDHI INSTITUTE OF


TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Bengaluru - 560032

2024
Data Structures Lab BSCL305

DATA STRUCTURES LABORATORY SEMESTER – III

Course Code: BCSL305 CIE Mark: 50


Number of Contact Hours/Week 0:0:2 SEE Marks:
50

Total Number of Lab Contact Hours 28 Exam Hours:


03 Credits – 1

Course Learning Objectives:

This laboratory course enables students to get practical experience in design, develop, implement,
analyse and evaluation/testing of

● Dynamic memory management

● Linear data structures and their applications such as stacks, queues and lists

● Non-Linear data structures and their applications such as trees and graphs

Descriptions (if any):

● Implement all the programs in “C” Programming Language and Linux OS.

Programs List:

1. Develop a Program in C for the following:


a. Declare a calendar as an array of 7 elements (A dynamically Created array) to represent 7
days of a week. Each Element of the array is a structure having three fields. The first field is
the name of the Day (A dynamically allocated String), The second field is the date of the Day
(A integer), the third field is the description of the activity for a particular day (A dynamically
allocated String).
b. Write functions create (), read () and display (); to create the calendar, to read the data from
the keyboard and to print weeks activity details report on screen.

2. Develop a Program in C for the following operations on Strings.


a. Read a main String (STR), a Pattern String (PAT) and a Replace String (REP)
b. Perform Pattern Matching Operation: Find and Replace all occurrences of PAT in STR
with REP if PAT exists in STR. Report suitable messages in case PAT does not exist in
STR Support the program with functions for each of the above operations. Don't use
Built-in functions.
3. Develop a menu driven Program in C for the following operations on STACK of Integers (Array
Implementation of Stack with maximum size MAX)
a. Push an Element on to Stack
b. Pop an Element from Stack
c. Demonstrate how Stack can be used to check Palindrome
d. Demonstrate Overflow and Underflow situations on Stack

Rajiv Gandhi Institute of Technology 2024


2
Data Structures Lab BSCL305

e. Display the status of Stack f. Exit Support the program with appropriate functions for
each of the above operations 15.09.2023 14.09.2023
4. Develop a Program in C for converting an Infix Expression to Postfix Expression. Program
should support for both parenthesized and free parenthesized expressions with the
operators: +, -, *, /, % (Remainder), ^ (Power) and alphanumeric operands.
5. Develop a Program in C for the following Stack Applications
a. Evaluation of Suffix expression with single digit operands and operators: +, -, *, /, %, ^
b. Solving Tower of Hanoi problem with n disks
6. Develop a menu driven Program in C for the following operations on Circular QUEUE of
Characters (Array Implementation of Queue with maximum size MAX)
a. Insert an Element on to Circular QUEUE
b. Delete an Element from Circular QUEUE
c. Demonstrate Overflow and Underflow situations on Circular QUEUE
d. Display the status of Circular QUEUE
e. Exit Support the program with appropriate functions for each of the above operations
7. Develop a menu driven Program in C for the following operations on Singly Linked List (SLL)
of Student Data with the fields: USN, Name, Programme, Sem, PhNo
a. Create a SLL of N Students Data by using front insertion.
b. Display the status of SLL and count the number of nodes in it
c. Perform Insertion / Deletion at End of SLL
d. Perform Insertion / Deletion at Front of SLL (Demonstration of stack)
e. Exit
8. Develop a menu driven Program in C for the following operations on Doubly Linked List (DLL)
of Employee Data with the fields: SSN, Name, Dept, Designation, Sal, PhNo
a. Create a DLL of N Employees Data by using end insertion.
b. Display the status of DLL and count the number of nodes in it
c. Perform Insertion and Deletion at End of DLL
d. Perform Insertion and Deletion at Front of DLL
e. Demonstrate how this DLL can be used as Double Ended Queue.
f. Exit
9. Develop a Program in C for the following operations on Singly Circular Linked List (SCLL) with
header nodes a. Represent and Evaluate a Polynomial P (x, y, z) = 6x 2 y 2 z-4yz 5 +3x 3
yz+2xy 5 z-2xyz 3 b. Find the sum of two polynomials POLY1(x, y, z) and POLY2(x, y, z) and
store the result in POLYSUM (x, y, z) Support the program with appropriate functions for
each of the above operations
10. Develop a menu driven Program in C for the following operations on Binary Search Tree
(BST) of Integers.
a. Create a BST of N Integers: 6, 9, 5, 2, 8, 15, 24, 14, 7, 8, 5, 2
b. Traverse the BST in In order, Preorder and Post Order
c. Search the BST for a given element (KEY) and report the appropriate message
d. Exit
11. Develop a Program in C for the following operations on Graph(G) of Cities
a. Create a Graph of N cities using Adjacency Matrix.
b. Print all the nodes reachable from a given starting node in a digraph using DFS/BFS
method.
12. Given a File of N employee records with a set K of Keys (4-digit) which uniquely determine
the records in file F. Assume that file F is maintained in memory by a Hash Table (HT) of m
memory locations with L as the set of memory addresses (2-digit) of locations in HT. Let the

Rajiv Gandhi Institute of Technology 2024


3
Data Structures Lab BSCL305

keys in K and addresses in L are Integers. Develop a Program in C that uses Hash Function H:
K →L as H(K)=K mod m (remainder method), and implement hashing technique to map a
given key K to the address space L. Resolve the collision (if any) using linear probing.

Laboratory Outcomes: The student should be able to:

● Analyse various linear and non-linear data structures


● Demonstrate the working nature of different types of data structures and their
applications
● Use appropriate searching and sorting algorithms for the give scenario.
● Apply the appropriate data structure for solving real world problems

Conduct of Practical Examination:

● Experiment distribution
o For laboratories having only one part: Students are allowed to pick one
experiment from the lot with equal opportunity.
o For laboratories having PART A and PART B: Students are allowed to pick one
experiment from PART A and one experiment from PART B, with equal
opportunity.
● Change of experiment is allowed only once and marks allotted for procedure to be made
zero of the changed part only.
● Marks Distribution (Need to change in accordance with university regulations)
a. For laboratories having only one part – Procedure + Execution + Viva-Voce:
15+70+15 = 100 Marks
b. For laboratories having PART A and PART B i. Part A – Procedure + Execution +
Viva = 6 + 28 + 6 = 40 Marks ii. Part B – Procedure + Execution + Viva = 9 + 42 + 9
= 60 Marks

Rajiv Gandhi Institute of Technology 2024


4
Data Structures Lab BSCL305

Program 1:

Develop a Program in C for the following:

a. Declare a calendar as an array of 7 elements (A dynamically Created array) to represent 7


days of a week. Each Element of the array is a structure having three fields. The first field is
the name of the Day (A dynamically allocated String), The second field is the date of the Day
(A integer), the third field is the description of the activity for a particular day (A dynamically
allocated String).
b. Write functions create (), read () and display (); to create the calendar, to read the data from
the keyboard and to print weeks activity details report on screen.

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

// Define the Day structure

typedef struct {

char *dayName;

int date;

char *activity;

} Day;

// Function prototypes

void create(Day **calendar);

void read(Day *calendar);

void display(const Day *calendar);

int main() {

// Create an array of 7 Day structures

Day *calendar = NULL;

create(&calendar);

read(calendar);

display(calendar);

// Free allocated memory

Rajiv Gandhi Institute of Technology 2024


5
Data Structures Lab BSCL305

for (int i = 0; i < 7; i++) {

free(calendar[i].dayName);

free(calendar[i].activity);

free(calendar);

return 0;

// Function to create the calendar array

void create(Day **calendar) {

*calendar = (Day *)malloc(7 * sizeof(Day));

if (*calendar == NULL) {

perror("Failed to allocate memory for calendar");

exit(EXIT_FAILURE);

const char *daysOfWeek[7] = {

"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"

};

for (int i = 0; i < 7; i++) {

(*calendar)[i].dayName = (char *)malloc((strlen(daysOfWeek[i]) + 1) * sizeof(char));

if ((*calendar)[i].dayName == NULL) {

perror("Failed to allocate memory for day name");

exit(EXIT_FAILURE);

strcpy((*calendar)[i].dayName, daysOfWeek[i]);

(*calendar)[i].date = 0; // Initialize date to 0

(*calendar)[i].activity = (char *)malloc(1 * sizeof(char)); // Initialize with empty string

Rajiv Gandhi Institute of Technology 2024


6
Data Structures Lab BSCL305

if ((*calendar)[i].activity == NULL) {

perror("Failed to allocate memory for activity");

exit(EXIT_FAILURE);

(*calendar)[i].activity[0] = '\0'; // Set the empty string

// Function to read data from the keyboard

void read(Day *calendar) {

char buffer[256];

for (int i = 0; i < 7; i++) {

printf("Enter date for %s: ", calendar[i].dayName);

if (scanf("%d", &calendar[i].date) != 1) {

fprintf(stderr, "Invalid input for date\n");

exit(EXIT_FAILURE);

// Clear the input buffer

while (getchar() != '\n');

printf("Enter activity for %s: ", calendar[i].dayName);

if (fgets(buffer, sizeof(buffer), stdin) == NULL) {

fprintf(stderr, "Error reading activity\n");

exit(EXIT_FAILURE);

// Remove the newline character from the input string

buffer[strcspn(buffer, "\n")] = '\0';

// Allocate memory for the activity

Rajiv Gandhi Institute of Technology 2024


7
Data Structures Lab BSCL305

calendar[i].activity = (char *)realloc(calendar[i].activity, (strlen(buffer) + 1) * sizeof(char));

if (calendar[i].activity == NULL) {

perror("Failed to allocate memory for activity");

exit(EXIT_FAILURE);

strcpy(calendar[i].activity, buffer);

// Function to display the calendar details

void display(const Day *calendar) {

printf("\n**********Weekly Calendar**********\n");

printf("%-10s%-8s %-10s\n","DAY","Date","Activity");

for (int i = 0; i < 7; i++) {

printf("%-10s %-5d %-100s\n", calendar[i].dayName, calendar[i].date,

(calendar[i].activity[0] == '\0') ? "NO Activity" : calendar[i].activity);

For linux OS

gcc -o calendar calendar.c

./calendar

Output:

Enter date for Monday: 1


Enter activity for Monday: playing tennis
Enter date for Tuesday: 2

Rajiv Gandhi Institute of Technology 2024


8
Data Structures Lab BSCL305

Enter activity for Tuesday:


Enter date for Wednesday: 2
Enter activity for Wednesday: attending classes
Enter date for Thursday: 3
Enter activity for Thursday: attending classes
Enter date for Friday: 5
Enter activity for Friday: playing cricket
Enter date for Saturday: 8
Enter activity for Saturday:
Enter date for Sunday: 5
Enter activity for Sunday: rest

**********Weekly Calendar**********
DAY Date Activity
Monday 1 playing tennis
Tuesday 2 NO Activity
Wednesday 2 attending classes
Thursday 3 attending classes
Friday 5 playing cricket
Saturday 8 NO Activity
Sunday 5 rest

Rajiv Gandhi Institute of Technology 2024


9
Data Structures Lab BSCL305

2. Develop a Program in C for the following operations on Strings.


a. Read a main String (STR), a Pattern String (PAT) and a Replace String (REP)
b. Perform Pattern Matching Operation: Find and Replace all occurrences of PAT in STR
with REP if PAT exists in STR. Report suitable messages in case PAT does not exist in STR
Support the program with functions for each of the above operations. Don't use Built-in
functions.

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

// Function prototypes

void readStrings(char **mainStr, char **patternStr, char **replaceStr);

int findPattern(const char *str, const char *pat);

void replacePattern(char *str, const char *pat, const char *rep);

void printString(const char *str);

int main() {

char *mainStr = NULL;

char *patternStr = NULL;

char *replaceStr = NULL;

// Read the strings from the user

readStrings(&mainStr, &patternStr, &replaceStr);

// Perform pattern matching and replacement

if (findPattern(mainStr, patternStr) != -1) {

replacePattern(mainStr, patternStr, replaceStr);

printf("Modified String: ");

printString(mainStr);

} else {

printf("Pattern not found in the main string.\n");

Rajiv Gandhi Institute of Technology 2024


10
Data Structures Lab BSCL305

// Free allocated memory

free(mainStr);

free(patternStr);

free(replaceStr);

return 0;

// Function to read strings from the user

void readStrings(char **mainStr, char **patternStr, char **replaceStr) {

char buffer[1000];

printf("Enter the main string: ");

fgets(buffer, sizeof(buffer), stdin);

buffer[strcspn(buffer, "\n")] = '\0'; // Remove the trailing newline

*mainStr = (char *)malloc((strlen(buffer) + 1) * sizeof(char));

strcpy(*mainStr, buffer);

printf("Enter the pattern string: ");

fgets(buffer, sizeof(buffer), stdin);

buffer[strcspn(buffer, "\n")] = '\0'; // Remove the trailing newline

*patternStr = (char *)malloc((strlen(buffer) + 1) * sizeof(char));

strcpy(*patternStr, buffer);

printf("Enter the replace string: ");

fgets(buffer, sizeof(buffer), stdin);

buffer[strcspn(buffer, "\n")] = '\0'; // Remove the trailing newline

*replaceStr = (char *)malloc((strlen(buffer) + 1) * sizeof(char));

strcpy(*replaceStr, buffer);

Rajiv Gandhi Institute of Technology 2024


11
Data Structures Lab BSCL305

// Function to find the pattern in the main string

int findPattern(const char *str, const char *pat) {

int strLen = strlen(str);

int patLen = strlen(pat);

for (int i = 0; i <= strLen - patLen; i++) {

int j;

for (j = 0; j < patLen; j++) {

if (str[i + j] != pat[j]) {

break;

if (j == patLen) {

return i;

return -1; // Pattern not found

// Function to replace the pattern with the replace string

void replacePattern(char *str, const char *pat, const char *rep) {

int strLen = strlen(str);

int patLen = strlen(pat);

int repLen = strlen(rep);

char *result = (char *)malloc((strLen + 1) * sizeof(char));

int i = 0, j = 0;

while (str[i]) {

if (findPattern(&str[i], pat) == 0) {

Rajiv Gandhi Institute of Technology 2024


12
Data Structures Lab BSCL305

strcpy(&result[j], rep);

j += repLen;

i += patLen;

} else {

result[j++] = str[i++];

result[j] = '\0';

strcpy(str, result);

free(result);

// Function to print a string

void printString(const char *str) {

printf("%s\n", str);

Output:

Enter the main string: The quick brown fox jumps over the lazy dog

Enter the pattern string: fox

Enter the replace string: cat

Modified String: The quick brown cat jumps over the lazy dog

Rajiv Gandhi Institute of Technology 2024


13
Data Structures Lab BSCL305

or
#include <stdio.h>
#include <string.h>

char str[50], pat[20], rep[20], res[50];


int c = 0, m = 0, i = 0, j = 0, k, flag = 0;

void stringmatch() {
while (str[c] != '\0') {
if (str[m] == pat[i]) {
i++;
m++;
if (pat[i] == '\0') {
flag = 1;
for (k = 0; rep[k] != '\0'; k++, j++) {
res[j] = rep[k];
}
i = 0;
c = m;
}
} else {
res[j] = str[c];
j++;
c++;
m = c;
i = 0;
}
}

Rajiv Gandhi Institute of Technology 2024


14
Data Structures Lab BSCL305

res[j] = '\0';
}

int main() {
printf("Enter the main string: ");
fgets(str, sizeof(str), stdin);
str[strcspn(str, "\n")] = '\0'; // Remove trailing newline

printf("Enter the pattern string: ");


fgets(pat, sizeof(pat), stdin);
pat[strcspn(pat, "\n")] = '\0'; // Remove trailing newline

printf("Enter the replace string: ");


fgets(rep, sizeof(rep), stdin);
rep[strcspn(rep, "\n")] = '\0'; // Remove trailing newline

printf("\nThe string before pattern match is: %s\n", str);


stringmatch();

if (flag == 1)
printf("The string after pattern match and replace is: %s\n", res);
else
printf("Pattern string is not found\n");

return 0;
}

Rajiv Gandhi Institute of Technology 2024


15
Data Structures Lab BSCL305

3. Develop a menu driven Program in C for the following operations on STACK of Integers (Array
Implementation of Stack with maximum size MAX) a. Push an Element on to Stack b. Pop an
Element from Stack c. Demonstrate how Stack can be used to check Palindrome d.
Demonstrate Overflow and Underflow situations on Stack e. Display the status of Stack f. Exit
Support the program with appropriate functions for each of the above operations

#include <stdio.h>

#include <stdlib.h>

#define MAX 100

// Stack structure

typedef struct {

int arr[MAX];

int top;

} Stack;

// Function prototypes

void push(Stack *s, int value);

int pop(Stack *s);

int isFull(Stack *s);

int isEmpty(Stack *s);

void display(Stack *s);

void checkPalindrome(Stack *s);

Rajiv Gandhi Institute of Technology 2024


16
Data Structures Lab BSCL305

void handleOverflow();

void handleUnderflow();

void menu();

int main() {

Stack s;

s.top = -1; // Initialize stack as empty

int choice, value;

while (1) {

menu();

printf("Enter your choice: ");

scanf("%d", &choice);

switch (choice) {

case 1:

if (isFull(&s)) {

handleOverflow();

} else {

printf("Enter value to push: ");

scanf("%d", &value);

push(&s, value);

break;

case 2:

if (isEmpty(&s)) {

handleUnderflow();

} else {

value = pop(&s);

printf("Popped value: %d\n", value);

Rajiv Gandhi Institute of Technology 2024


17
Data Structures Lab BSCL305

break;

case 3:

checkPalindrome(&s);

break;

case 4:

display(&s);

break;

case 5:

exit(0);

default:

printf("Invalid choice. Please try again.\n");

return 0;

// Function to push an element onto the stack

void push(Stack *s, int value) {

s->arr[++(s->top)] = value;

printf("Pushed %d onto stack.\n", value);

// Function to pop an element from the stack

int pop(Stack *s) {

return s->arr[(s->top)--];

// Function to check if the stack is full

int isFull(Stack *s) {

Rajiv Gandhi Institute of Technology 2024


18
Data Structures Lab BSCL305

return s->top == MAX - 1;

// Function to check if the stack is empty

int isEmpty(Stack *s) {

return s->top == -1;

// Function to display the stack status

void display(Stack *s) {

if (isEmpty(s)) {

printf("Stack is empty.\n");

return;

printf("Stack elements are:\n");

for (int i = s->top; i >= 0; i--) {

printf("%d\n", s->arr[i]);

// Function to check if the stack is a palindrome

void checkPalindrome(Stack *s) {

if (isEmpty(s)) {

printf("Stack is empty.\n");

return;

int i = 0, j = s->top;

int isPal = 1;

// Check for palindrome

while (i < j) {

Rajiv Gandhi Institute of Technology 2024


19
Data Structures Lab BSCL305

if (s->arr[i] != s->arr[j]) {

isPal = 0;

break;

i++;

j--;

if (isPal) {

printf("The stack is a palindrome.\n");

} else {

printf("The stack is not a palindrome.\n");

// Function to handle stack overflow

void handleOverflow() {

printf("Error: Stack overflow! Cannot push more elements.\n");

// Function to handle stack underflow

void handleUnderflow() {

printf("Error: Stack underflow! Cannot pop from an empty stack.\n");

// Function to display the menu

void menu() {

printf("\nMenu:\n");

printf("1. Push an Element\n");

printf("2. Pop an Element\n");

printf("3. Check Palindrome\n");

Rajiv Gandhi Institute of Technology 2024


20
Data Structures Lab BSCL305

printf("4. Display Stack\n");

printf("5. Exit\n");

gcc -o stack_program stack_program.c

./stack_program

Output:

Menu:

1. Push an Element

2. Pop an Element

3. Check Palindrome

4. Display Stack

5. Exit

Enter your choice: 4

Stack is empty.

Menu:

1. Push an Element

2. Pop an Element

3. Check Palindrome

4. Display Stack

5. Exit

Enter your choice: 1

Enter value to push: 23

Pushed 23 onto stack.

Menu:

1. Push an Element

2. Pop an Element

Rajiv Gandhi Institute of Technology 2024


21
Data Structures Lab BSCL305

3. Check Palindrome

4. Display Stack

5. Exit

Enter your choice: 4

Stack elements are:

23

Menu:

1. Push an Element

2. Pop an Element

3. Check Palindrome

4. Display Stack

5. Exit

Enter your choice: 1

Enter value to push: 23

Pushed 23 onto stack.

Menu:

1. Push an Element

2. Pop an Element

3. Check Palindrome

4. Display Stack

5. Exit

Enter your choice: 1

Enter value to push: 33

Pushed 33 onto stack.

Menu:

1. Push an Element

2. Pop an Element

3. Check Palindrome

Rajiv Gandhi Institute of Technology 2024


22
Data Structures Lab BSCL305

4. Display Stack

5. Exit

Enter your choice: 4

Stack elements are:

33

23

23

Menu:

1. Push an Element

2. Pop an Element

3. Check Palindrome

4. Display Stack

5. Exit

Enter your choice: 2

Popped value: 33

Menu:

1. Push an Element

2. Pop an Element

3. Check Palindrome

4. Display Stack

5. Exit

Enter your choice: 5

Rajiv Gandhi Institute of Technology 2024


23
Data Structures Lab BSCL305

4. Develop a Program in C for converting an Infix Expression to Postfix Expression. Program


should support for both parenthesized and free parenthesized expressions with the
operators: +, -, *, /, % (Remainder), ^ (Power) and alphanumeric operands.

#include <stdio.h>

#include <stdlib.h>

#include <ctype.h>

#include <string.h>

#define MAX 100

// Stack structure for operators

typedef struct {

char arr[MAX];

int top;

} CharStack;

// Stack operations

void push(CharStack *s, char c);

char pop(CharStack *s);

char peek(CharStack *s);

int isEmpty(CharStack *s);

int isFull(CharStack *s);

// Operator precedence

int precedence(char op);

Rajiv Gandhi Institute of Technology 2024


24
Data Structures Lab BSCL305

int isOperator(char c);

void infixToPostfix(const char *infix, char *postfix);

int main() {

char infix[MAX], postfix[MAX];

printf("Enter infix expression: ");

fgets(infix, sizeof(infix), stdin);

infix[strcspn(infix, "\n")] = '\0'; // Remove the trailing newline

infixToPostfix(infix, postfix);

printf("Postfix expression: %s\n", postfix);

return 0;

// Function to push an element onto the stack

void push(CharStack *s, char c) {

if (isFull(s)) {

fprintf(stderr, "Stack overflow\n");

exit(EXIT_FAILURE);

s->arr[++(s->top)] = c;

// Function to pop an element from the stack

char pop(CharStack *s) {

if (isEmpty(s)) {

fprintf(stderr, "Stack underflow\n");

exit(EXIT_FAILURE);

Rajiv Gandhi Institute of Technology 2024


25
Data Structures Lab BSCL305

return s->arr[(s->top)--];

// Function to peek at the top element of the stack

char peek(CharStack *s) {

if (isEmpty(s)) {

return '\0'; // Return null character if stack is empty

return s->arr[s->top];

// Function to check if the stack is empty

int isEmpty(CharStack *s) {

return s->top == -1;

// Function to check if the stack is full

int isFull(CharStack *s) {

return s->top == MAX - 1;

// Function to return the precedence of an operator

int precedence(char op) {

switch (op) {

case '+':

case '-':

return 1;

case '*':

case '/':

case '%':

return 2;

Rajiv Gandhi Institute of Technology 2024


26
Data Structures Lab BSCL305

case '^':

return 3;

default:

return 0;

// Function to check if a character is an operator

int isOperator(char c) {

return (c == '+' || c == '-' || c == '*' || c == '/' || c == '%' || c == '^');

// Function to convert infix expression to postfix expression

void infixToPostfix(const char *infix, char *postfix) {

CharStack s;

s.top = -1; // Initialize stack

int j = 0;

for (int i = 0; infix[i] != '\0'; i++) {

char c = infix[i];

if (isalnum(c)) {

postfix[j++] = c; // Add operand to postfix expression

} else if (c == '(') {

push(&s, c); // Push '(' onto stack

} else if (c == ')') {

while (!isEmpty(&s) && peek(&s) != '(') {

postfix[j++] = pop(&s); // Pop operators from stack to postfix

pop(&s); // Pop '(' from stack

} else if (isOperator(c)) {

Rajiv Gandhi Institute of Technology 2024


27
Data Structures Lab BSCL305

while (!isEmpty(&s) && precedence(c) <= precedence(peek(&s))) {

postfix[j++] = pop(&s); // Pop operators from stack to postfix

push(&s, c); // Push current operator onto stack

// Pop all the remaining operators in the stack

while (!isEmpty(&s)) {

postfix[j++] = pop(&s);

postfix[j] = '\0'; // Null-terminate the postfix expression

Output :

Enter infix expression: a + b * (c / d)

Postfix expression: abcd/*+

Rajiv Gandhi Institute of Technology 2024


28
Data Structures Lab BSCL305

5. Develop a Program in C for the following Stack Applications


a. Evaluation of Suffix expression with single digit operands and operators: +, -, *, /, %, ^
b. Solving Tower of Hanoi problem with n disks

#include <stdio.h>

#include <stdlib.h>

#include <ctype.h>

#include <string.h>

#include <math.h> // Include the math header for pow function

#define MAX 100

typedef struct {

int top;

int items[MAX];

} Stack;

void push(Stack *s, int value) {

if (s->top == (MAX - 1)) {

printf("Stack is full\n");

return;

s->items[++(s->top)] = value;

int pop(Stack *s) {

if (s->top == -1) {

Rajiv Gandhi Institute of Technology 2024


29
Data Structures Lab BSCL305

printf("Stack is empty\n");

exit(1); // Exit on stack underflow

return s->items[(s->top)--];

int evaluateSuffix(char *expr) {

Stack s;

s.top = -1;

int i, op1, op2, result;

char *token;

char delim[] = " ";

token = strtok(expr, delim); // Tokenize based on space

while (token != NULL) {

if (isdigit(token[0])) {

push(&s, atoi(token)); // Convert token to integer and push onto stack

} else {

op2 = pop(&s);

op1 = pop(&s);

switch (token[0]) {

case '+': result = op1 + op2; break;

case '-': result = op1 - op2; break;

case '*': result = op1 * op2; break;

case '/': result = op1 / op2; break;

case '%': result = op1 % op2; break;

case '^': result = (int)pow(op1, op2); break;

default:

printf("Invalid operator\n");

exit(1);

Rajiv Gandhi Institute of Technology 2024


30
Data Structures Lab BSCL305

push(&s, result);

token = strtok(NULL, delim); // Get next token

return pop(&s); // Final result

int main() {

char expr[MAX];

printf("Enter the suffix expression: ");

fgets(expr, MAX, stdin);

expr[strcspn(expr, "\n")] = 0; // Remove newline character

int result = evaluateSuffix(expr);

printf("Result: %d\n", result);

return 0;

Output:

1.

Enter the suffix expression: 3 4 + 2 * 7 /

Result: 2

2.

Enter the suffix expression: 5 1 2 + 4 * + 3 -

Result: 14

Rajiv Gandhi Institute of Technology 2024


31
Data Structures Lab BSCL305

b)

#include <stdio.h>

void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod) {

if (n == 1) {

printf("Move disk 1 from rod %c to rod %c\n", from_rod, to_rod);

return;

towerOfHanoi(n - 1, from_rod, aux_rod, to_rod);

printf("Move disk %d from rod %c to rod %c\n", n, from_rod, to_rod);

towerOfHanoi(n - 1, aux_rod, to_rod, from_rod);

int main() {

int n;

printf("Enter the number of disks: ");

scanf("%d", &n);

towerOfHanoi(n, 'A', 'C', 'B'); // A, B, and C are names of rods

return 0;

Output:

Enter the number of disks: 4

Move disk 1 from rod A to rod B

Move disk 2 from rod A to rod C

Move disk 1 from rod B to rod C

Move disk 3 from rod A to rod B

Move disk 1 from rod C to rod A

Rajiv Gandhi Institute of Technology 2024


32
Data Structures Lab BSCL305

Move disk 2 from rod C to rod B

Move disk 1 from rod A to rod B

Move disk 4 from rod A to rod C

Move disk 1 from rod B to rod C

Move disk 2 from rod B to rod A

Move disk 1 from rod C to rod A

Move disk 3 from rod B to rod C

Move disk 1 from rod A to rod B

Move disk 2 from rod A to rod C

Move disk 1 from rod B to rod C

Rajiv Gandhi Institute of Technology 2024


33
Data Structures Lab BSCL305

6. Develop a menu driven Program in C for the following operations on Circular QUEUE of Characters
(Array Implementation of Queue with maximum size MAX)

A. Insert an Element on to Circular QUEUE


B. Delete an Element from Circular QUEUE
C. Demonstrate Overflow and Underflow situations on Circular QUEUE
D. Display the status of Circular QUEUE

#include <stdio.h>

#include <stdlib.h>

#define MAX 3 // Define maximum size of the circular queue

typedef struct {

char items[MAX];

int front, rear, size;

} CircularQueue;

// Function prototypes

void initializeQueue(CircularQueue *q);

int isFull(CircularQueue *q);

int isEmpty(CircularQueue *q);

void insert(CircularQueue *q, char item);

char delete(CircularQueue *q);

void display(CircularQueue *q);

void demonstrateOverflowUnderflow(CircularQueue *q);

int main() {

CircularQueue queue;

Rajiv Gandhi Institute of Technology 2024


34
Data Structures Lab BSCL305

int choice;

char item;

initializeQueue(&queue);

while (1) {

printf("\nCircular Queue Operations Menu:\n");

printf("1. Insert an Element\n");

printf("2. Delete an Element\n");

printf("3. Demonstrate Overflow and Underflow\n");

printf("4. Display Queue Status\n");

printf("5. Exit\n");

printf("Enter your choice: ");

scanf("%d", &choice);

switch (choice) {

case 1:

if (isFull(&queue)) {

printf("Queue is full! Cannot insert element.\n");

} else {

printf("Enter a character to insert: ");

scanf(" %c", &item); // Space before %c to ignore whitespace

insert(&queue, item);

break;

case 2:

if (isEmpty(&queue)) {

printf("Queue is empty! Cannot delete element.\n");

} else {

item = delete(&queue);

printf("Deleted element: %c\n", item);

Rajiv Gandhi Institute of Technology 2024


35
Data Structures Lab BSCL305

break;

case 3:

demonstrateOverflowUnderflow(&queue);

break;

case 4:

display(&queue);

break;

case 5:

exit(0);

default:

printf("Invalid choice! Please enter a number between 1 and 5.\n");

return 0;

void initializeQueue(CircularQueue *q) {

q->front = 0;

q->rear = -1;

q->size = 0;

int isFull(CircularQueue *q) {

return q->size == MAX;

int isEmpty(CircularQueue *q) {

return q->size == 0;

Rajiv Gandhi Institute of Technology 2024


36
Data Structures Lab BSCL305

void insert(CircularQueue *q, char item) {

q->rear = (q->rear + 1) % MAX;

q->items[q->rear] = item;

q->size++;

printf("Inserted element: %c\n", item);

char delete(CircularQueue *q) {

char item = q->items[q->front];

q->front = (q->front + 1) % MAX;

q->size--;

return item;

void display(CircularQueue *q) {

if (isEmpty(q)) {

printf("Queue is empty.\n");

return;

printf("Queue elements: ");

int i, count;

for (i = 0, count = q->front; i < q->size; i++) {

printf("%c ", q->items[count]);

count = (count + 1) % MAX;

printf("\n");

void demonstrateOverflowUnderflow(CircularQueue *q) {

Rajiv Gandhi Institute of Technology 2024


37
Data Structures Lab BSCL305

printf("Demonstrating Overflow and Underflow...\n");

// Try inserting elements until the queue is full

for (int i = 0; i < MAX; i++) {

insert(q, 'A' + i);

insert(q, 'Z'); // This should show that the queue is full

// Try deleting all elements from the queue

while (!isEmpty(q)) {

delete(q);

delete(q); // This should show that the queue is empty

Output:

Circular Queue Operations Menu:

1. Insert an Element

2. Delete an Element

3. Demonstrate Overflow and Underflow

4. Display Queue Status

5. Exit

Enter your choice: 1

Enter a character to insert: a

Inserted element: a

Circular Queue Operations Menu:

1. Insert an Element

2. Delete an Element

3. Demonstrate Overflow and Underflow

Rajiv Gandhi Institute of Technology 2024


38
Data Structures Lab BSCL305

4. Display Queue Status

5. Exit

Enter your choice: 1

Enter a character to insert: b

Inserted element: b

Circular Queue Operations Menu:

1. Insert an Element

2. Delete an Element

3. Demonstrate Overflow and Underflow

4. Display Queue Status

5. Exit

Enter your choice: 1

Enter a character to insert: c

Inserted element: c

Circular Queue Operations Menu:

1. Insert an Element

2. Delete an Element

3. Demonstrate Overflow and Underflow

4. Display Queue Status

5. Exit

Enter your choice: 1

Queue is full! Cannot insert element.

Circular Queue Operations Menu:

1. Insert an Element

2. Delete an Element

3. Demonstrate Overflow and Underflow

4. Display Queue Status

5. Exit

Rajiv Gandhi Institute of Technology 2024


39
Data Structures Lab BSCL305

Enter your choice: 4

Queue elements: a b c

Circular Queue Operations Menu:

1. Insert an Element

2. Delete an Element

3. Demonstrate Overflow and Underflow

4. Display Queue Status

5. Exit

Enter your choice: 5

Rajiv Gandhi Institute of Technology 2024


40
Data Structures Lab BSCL305

7. Develop a menu driven Program in C for the following operations on Singly Linked List (SLL) of
Student Data with the fields: USN, Name, Programme, Sem, PhNo

a. Create a SLL of N Students Data by using front insertion.


b. Display the status of SLL and count the number of nodes in it
c. Perform Insertion / Deletion at End of SLL
d. Perform Insertion / Deletion at Front of SLL (Demonstration of stack)
e. Exit

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

// Define maximum sizes


#define MAX_NAME_LENGTH 100
#define MAX_PROG_LENGTH 50
#define MAX_PHNO_LENGTH 15

// Define the structure for student data


typedef struct Student {
char usn[15];
char name[MAX_NAME_LENGTH];
char programme[MAX_PROG_LENGTH];
int sem;
char phno[MAX_PHNO_LENGTH];
struct Student *next;
} Student;

// Function prototypes
Student* createStudent();
void displayList(Student *head);
void insertFront(Student **head, Student *newStudent);
void insertEnd(Student **head, Student *newStudent);
void deleteFront(Student **head);
void deleteEnd(Student **head);
int countNodes(Student *head);
void freeList(Student *head);

int main() {
Student *head = NULL; // Initialize head of the list
int choice;

Rajiv Gandhi Institute of Technology 2024


41
Data Structures Lab BSCL305

Student *newStudent;
int nodeCount;

while (1) {
printf("\nSingly Linked List Operations Menu:\n");
printf("1. Create SLL of N Students (Front Insertion)\n");
printf("2. Display SLL and Count Nodes\n");
printf("3. Insert at End of SLL\n");
printf("4. Delete from End of SLL\n");
printf("5. Insert at Front of SLL\n");
printf("6. Delete from Front of SLL\n");
printf("7. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
getchar(); // Consume newline character left by scanf

switch (choice) {
case 1:
{
int n;
printf("Enter the number of students: ");
scanf("%d", &n);
getchar(); // Consume newline character

for (int i = 0; i < n; i++) {


newStudent = createStudent();
insertFront(&head, newStudent);
}
printf("SLL created with %d students using front insertion.\n", n);
}
break;

case 2:
displayList(head);
nodeCount = countNodes(head);
printf("Number of nodes: %d\n", nodeCount);
break;

case 3:
newStudent = createStudent();
insertEnd(&head, newStudent);
printf("Inserted student at the end of the list.\n");
break;

case 4:
deleteEnd(&head);
printf("Deleted student from the end of the list.\n");
break;

Rajiv Gandhi Institute of Technology 2024


42
Data Structures Lab BSCL305

case 5:
newStudent = createStudent();
insertFront(&head, newStudent);
printf("Inserted student at the front of the list.\n");
break;

case 6:
deleteFront(&head);
printf("Deleted student from the front of the list.\n");
break;

case 7:
freeList(head);
exit(0);

default:
printf("Invalid choice! Please enter a number between 1 and 7.\n");
}
}

return 0;
}

// Function to create a new student


Student* createStudent() {
Student *newStudent = (Student*)malloc(sizeof(Student));
if (!newStudent) {
printf("Memory allocation failed!\n");
exit(1);
}

printf("Enter USN: ");


fgets(newStudent->usn, sizeof(newStudent->usn), stdin);
newStudent->usn[strcspn(newStudent->usn, "\n")] = '\0'; // Remove newline character

printf("Enter Name: ");


fgets(newStudent->name, sizeof(newStudent->name), stdin);
newStudent->name[strcspn(newStudent->name, "\n")] = '\0'; // Remove newline character

printf("Enter Programme: ");


fgets(newStudent->programme, sizeof(newStudent->programme), stdin);
newStudent->programme[strcspn(newStudent->programme, "\n")] = '\0'; // Remove newline
character

printf("Enter Semester: ");


scanf("%d", &newStudent->sem);
getchar(); // Consume newline character

Rajiv Gandhi Institute of Technology 2024


43
Data Structures Lab BSCL305

printf("Enter Phone Number: ");


fgets(newStudent->phno, sizeof(newStudent->phno), stdin);
newStudent->phno[strcspn(newStudent->phno, "\n")] = '\0'; // Remove newline character

newStudent->next = NULL;
return newStudent;
}

// Function to display the linked list


void displayList(Student *head) {
if (head == NULL) {
printf("The list is empty.\n");
return;
}

printf("Student List:\n");
Student *temp = head;
while (temp != NULL) {
printf("USN: %s\n", temp->usn);
printf("Name: %s\n", temp->name);
printf("Programme: %s\n", temp->programme);
printf("Semester: %d\n", temp->sem);
printf("Phone Number: %s\n", temp->phno);
printf("-------------\n");
temp = temp->next;
}
}

// Function to insert a student at the front of the list


void insertFront(Student **head, Student *newStudent) {
newStudent->next = *head;
*head = newStudent;
}

// Function to insert a student at the end of the list


void insertEnd(Student **head, Student *newStudent) {
if (*head == NULL) {
*head = newStudent;
return;
}

Student *temp = *head;


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

Rajiv Gandhi Institute of Technology 2024


44
Data Structures Lab BSCL305

// Function to delete a student from the front of the list


void deleteFront(Student **head) {
if (*head == NULL) {
printf("The list is empty. Cannot delete.\n");
return;
}

Student *temp = *head;


*head = (*head)->next;
free(temp);
}

// Function to delete a student from the end of the list


void deleteEnd(Student **head) {
if (*head == NULL) {
printf("The list is empty. Cannot delete.\n");
return;
}

if ((*head)->next == NULL) {
free(*head);
*head = NULL;
return;
}

Student *temp = *head;


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

// Function to count the number of nodes in the list


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

// Function to free all nodes in the list


void freeList(Student *head) {
Student *temp;

Rajiv Gandhi Institute of Technology 2024


45
Data Structures Lab BSCL305

while (head != NULL) {


temp = head;
head = head->next;
free(temp);
}
}

Output:

Singly Linked List Operations Menu:


1. Create SLL of N Students (Front Insertion)
2. Display SLL and Count Nodes
3. Insert at End of SLL
4. Delete from End of SLL
5. Insert at Front of SLL
6. Delete from Front of SLL
7. Exit
Enter your choice: 1
Enter the number of students: 2
Enter USN: 23
Enter Name: Sam
Enter Programme: comp
Enter Semester: 3
Enter Phone Number: 1111
Enter USN: 34
Enter Name: Shyam
Enter Programme: be
Enter Semester: 3
Enter Phone Number: 2222
SLL created with 2 students using front insertion.

Singly Linked List Operations Menu:


1. Create SLL of N Students (Front Insertion)
2. Display SLL and Count Nodes
3. Insert at End of SLL
4. Delete from End of SLL
5. Insert at Front of SLL
6. Delete from Front of SLL
7. Exit

Rajiv Gandhi Institute of Technology 2024


46
Data Structures Lab BSCL305

8. Develop a menu driven Program in C for the following operations on Doubly Linked List (DLL) of
Employee Data with the fields: SSN, Name, Dept, Designation, Sal, PhNo

A. Create a DLL of N Employees Data by using end insertion.


B. Display the status of DLL and count the number of nodes in it
C. Perform Insertion and Deletion at End of DLL
D. Perform Insertion and Deletion at Front of DLL
E. Demonstrate how this DLL can be used as Double Ended Queue.
F. Exit

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#define MAX_NAME_LENGTH 100

#define MAX_DEPT_LENGTH 50

#define MAX_DESG_LENGTH 50

#define MAX_PHNO_LENGTH 15

// Define the structure for employee data

typedef struct Employee {

char ssn[15];

char name[MAX_NAME_LENGTH];

char dept[MAX_DEPT_LENGTH];

char designation[MAX_DESG_LENGTH];

float sal;

char phno[MAX_PHNO_LENGTH];

struct Employee *next;

struct Employee *prev;

} Employee;

// Function prototypes

Employee* createEmployee();

void displayList(Employee *head);

Rajiv Gandhi Institute of Technology 2024


47
Data Structures Lab BSCL305

void insertEnd(Employee **head, Employee **tail, Employee *newEmployee);

void deleteEnd(Employee **head, Employee **tail);

void insertFront(Employee **head, Employee **tail, Employee *newEmployee);

void deleteFront(Employee **head, Employee **tail);

int countNodes(Employee *head);

void demonstrateDeque(Employee *head, Employee *tail);

void freeList(Employee *head);

int main() {

Employee *head = NULL, *tail = NULL;

int choice;

Employee *newEmployee;

int nodeCount;

while (1) {

printf("\nDoubly Linked List Operations Menu:\n");

printf("1. Create DLL of N Employees (End Insertion)\n");

printf("2. Display DLL and Count Nodes\n");

printf("3. Insert at End of DLL\n");

printf("4. Delete from End of DLL\n");

printf("5. Insert at Front of DLL\n");

printf("6. Delete from Front of DLL\n");

printf("7. Demonstrate DLL as Double Ended Queue\n");

printf("8. Exit\n");

printf("Enter your choice: ");

scanf("%d", &choice);

getchar(); // Consume newline character

switch (choice) {

case 1:

Rajiv Gandhi Institute of Technology 2024


48
Data Structures Lab BSCL305

int n;

printf("Enter the number of employees: ");

scanf("%d", &n);

getchar(); // Consume newline character

for (int i = 0; i < n; i++) {

newEmployee = createEmployee();

insertEnd(&head, &tail, newEmployee);

printf("DLL created with %d employees using end insertion.\n", n);

break;

case 2:

displayList(head);

nodeCount = countNodes(head);

printf("Number of nodes: %d\n", nodeCount);

break;

case 3:

newEmployee = createEmployee();

insertEnd(&head, &tail, newEmployee);

printf("Inserted employee at the end of the list.\n");

break;

case 4:

deleteEnd(&head, &tail);

printf("Deleted employee from the end of the list.\n");

break;

case 5:

Rajiv Gandhi Institute of Technology 2024


49
Data Structures Lab BSCL305

newEmployee = createEmployee();

insertFront(&head, &tail, newEmployee);

printf("Inserted employee at the front of the list.\n");

break;

case 6:

deleteFront(&head, &tail);

printf("Deleted employee from the front of the list.\n");

break;

case 7:

demonstrateDeque(head, tail);

break;

case 8:

freeList(head);

exit(0);

default:

printf("Invalid choice! Please enter a number between 1 and 8.\n");

return 0;

// Function to create a new employee

Employee* createEmployee() {

Employee *newEmployee = (Employee*)malloc(sizeof(Employee));

if (!newEmployee) {

printf("Memory allocation failed!\n");

Rajiv Gandhi Institute of Technology 2024


50
Data Structures Lab BSCL305

exit(1);

printf("Enter SSN: ");

fgets(newEmployee->ssn, sizeof(newEmployee->ssn), stdin);

newEmployee->ssn[strcspn(newEmployee->ssn, "\n")] = '\0'; // Remove newline character

printf("Enter Name: ");

fgets(newEmployee->name, sizeof(newEmployee->name), stdin);

newEmployee->name[strcspn(newEmployee->name, "\n")] = '\0'; // Remove newline character

printf("Enter Department: ");

fgets(newEmployee->dept, sizeof(newEmployee->dept), stdin);

newEmployee->dept[strcspn(newEmployee->dept, "\n")] = '\0'; // Remove newline character

printf("Enter Designation: ");

fgets(newEmployee->designation, sizeof(newEmployee->designation), stdin);

newEmployee->designation[strcspn(newEmployee->designation, "\n")] = '\0'; // Remove newline


character

printf("Enter Salary: ");

scanf("%f", &newEmployee->sal);

getchar(); // Consume newline character

printf("Enter Phone Number: ");

fgets(newEmployee->phno, sizeof(newEmployee->phno), stdin);

newEmployee->phno[strcspn(newEmployee->phno, "\n")] = '\0'; // Remove newline character

newEmployee->next = NULL;

newEmployee->prev = NULL;

return newEmployee;

Rajiv Gandhi Institute of Technology 2024


51
Data Structures Lab BSCL305

// Function to display the doubly linked list

void displayList(Employee *head) {

if (head == NULL) {

printf("The list is empty.\n");

return;

printf("Employee List:\n");

Employee *temp = head;

while (temp != NULL) {

printf("SSN: %s\n", temp->ssn);

printf("Name: %s\n", temp->name);

printf("Department: %s\n", temp->dept);

printf("Designation: %s\n", temp->designation);

printf("Salary: %.2f\n", temp->sal);

printf("Phone Number: %s\n", temp->phno);

printf("-------------\n");

temp = temp->next;

// Function to insert an employee at the end of the list

void insertEnd(Employee **head, Employee **tail, Employee *newEmployee) {

if (*tail == NULL) {

*head = *tail = newEmployee;

return;

(*tail)->next = newEmployee;

Rajiv Gandhi Institute of Technology 2024


52
Data Structures Lab BSCL305

newEmployee->prev = *tail;

*tail = newEmployee;

// Function to delete an employee from the end of the list

void deleteEnd(Employee **head, Employee **tail) {

if (*tail == NULL) {

printf("The list is empty. Cannot delete.\n");

return;

Employee *temp = *tail;

if (*head == *tail) { // Only one element in the list

*head = *tail = NULL;

} else {

*tail = (*tail)->prev;

(*tail)->next = NULL;

free(temp);

// Function to insert an employee at the front of the list

void insertFront(Employee **head, Employee **tail, Employee *newEmployee) {

if (*head == NULL) {

*head = *tail = newEmployee;

return;

newEmployee->next = *head;

(*head)->prev = newEmployee;

*head = newEmployee;

Rajiv Gandhi Institute of Technology 2024


53
Data Structures Lab BSCL305

// Function to delete an employee from the front of the list

void deleteFront(Employee **head, Employee **tail) {

if (*head == NULL) {

printf("The list is empty. Cannot delete.\n");

return;

Employee *temp = *head;

if (*head == *tail) { // Only one element in the list

*head = *tail = NULL;

} else {

*head = (*head)->next;

(*head)->prev = NULL;

free(temp);

// Function to count the number of nodes in the list

int countNodes(Employee *head) {

int count = 0;

Employee *temp = head;

while (temp != NULL) {

count++;

temp = temp->next;

return count;

// Function to demonstrate DLL as a double-ended queue

Rajiv Gandhi Institute of Technology 2024


54
Data Structures Lab BSCL305

void demonstrateDeque(Employee *head, Employee *tail) {

printf("Demonstrating DLL as a Double Ended Queue:\n");

// Insertion at front

printf("Inserting at front:\n");

Employee *newEmployee = createEmployee();

insertFront(&head, &tail, newEmployee);

displayList(head);

// Insertion at end

printf("Inserting at end:\n");

newEmployee = createEmployee();

insertEnd(&head, &tail, newEmployee);

displayList(head);

// Deletion from front

printf("Deleting from front:\n");

deleteFront(&head, &tail);

displayList(head);

// Deletion from end

printf("Deleting from end:\n");

deleteEnd(&head, &tail);

displayList(head);

// Function to free all nodes in the list

void freeList(Employee *head) {

Employee *temp;

while (head != NULL) {

temp = head;

Rajiv Gandhi Institute of Technology 2024


55
Data Structures Lab BSCL305

head = head->next;

free(temp);

Output:

Doubly Linked List Operations Menu:

1. Create DLL of N Employees (End Insertion)

2. Display DLL and Count Nodes

3. Insert at End of DLL

4. Delete from End of DLL

5. Insert at Front of DLL

6. Delete from Front of DLL

7. Demonstrate DLL as Double Ended Queue

8. Exit

Enter your choice: 1

Enter the number of employees: 2

Enter SSN: 2

Enter Name: Ram

Enter Department: CSE

Enter Designation: AP

Enter Salary: 10000

Enter Phone Number: 2222

Enter SSN: 4

Enter Name: Gyan

Enter Department: EC

Enter Designation: AP

Enter Salary: 20000

Enter Phone Number: 22333

Rajiv Gandhi Institute of Technology 2024


56
Data Structures Lab BSCL305

DLL created with 2 employees using end insertion.

Doubly Linked List Operations Menu:

1. Create DLL of N Employees (End Insertion)

2. Display DLL and Count Nodes

3. Insert at End of DLL

4. Delete from End of DLL

5. Insert at Front of DLL

6. Delete from Front of DLL

7. Demonstrate DLL as Double Ended Queue

8. Exit

Enter your choice: 2

Employee List:

SSN: 2

Name: Ram

Department: CSE

Designation: AP

Salary: 10000.00

Phone Number: 2222

-------------

SSN: 4

Name: Gyan

Department: EC

Designation: AP

Salary: 20000.00

Phone Number: 22333

-------------

Number of nodes: 2

Doubly Linked List Operations Menu:

1. Create DLL of N Employees (End Insertion)

Rajiv Gandhi Institute of Technology 2024


57
Data Structures Lab BSCL305

2. Display DLL and Count Nodes

3. Insert at End of DLL

4. Delete from End of DLL

5. Insert at Front of DLL

6. Delete from Front of DLL

7. Demonstrate DLL as Double Ended Queue

8. Exit

Enter your choice: 6

Deleted employee from the front of the list.

Doubly Linked List Operations Menu:

1. Create DLL of N Employees (End Insertion)

2. Display DLL and Count Nodes

3. Insert at End of DLL

4. Delete from End of DLL

5. Insert at Front of DLL

6. Delete from Front of DLL

7. Demonstrate DLL as Double Ended Queue

8. Exit

Enter your choice: 2

Employee List:

SSN: 4

Name: Gyan

Department: EC

Designation: AP

Salary: 20000.00

Phone Number: 22333

-------------

Number of nodes: 1

Doubly Linked List Operations Menu:

Rajiv Gandhi Institute of Technology 2024


58
Data Structures Lab BSCL305

1. Create DLL of N Employees (End Insertion)

2. Display DLL and Count Nodes

3. Insert at End of DLL

4. Delete from End of DLL

5. Insert at Front of DLL

6. Delete from Front of DLL

7. Demonstrate DLL as Double Ended Queue

8. Exit

Enter your choice: 8

Rajiv Gandhi Institute of Technology 2024


59
Data Structures Lab BSCL305

9. Develop a Program in C for the following operations on Singly Circular Linked List (SCLL) with
header nodes a. Represent and Evaluate a Polynomial P (x, y, z) = 6x 2 y 2 z-4yz 5 +3x 3 yz+2xy 5
z-2xyz 3 b. Find the sum of two polynomials POLY1(x, y, z) and POLY2(x, y, z) and store the result in
POLYSUM (x, y, z) Support the program with appropriate functions for each of the above operations

#include <stdio.h>

#include <stdlib.h>

#include <math.h> // Include the math library for pow function

// Node structure for singly circular linked list

typedef struct Node {

int coeff;

int x_exp;

int y_exp;

int z_exp;

struct Node *next;

} Node;

// Function to create a new node

Node* createNode(int coeff, int x_exp, int y_exp, int z_exp) {

Node* newNode = (Node*)malloc(sizeof(Node));

newNode->coeff = coeff;

newNode->x_exp = x_exp;

newNode->y_exp = y_exp;

newNode->z_exp = z_exp;

newNode->next = newNode; // Initially points to itself

return newNode;

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

Rajiv Gandhi Institute of Technology 2024


60
Data Structures Lab BSCL305

void insertNode(Node** header, int coeff, int x_exp, int y_exp, int z_exp) {

Node* newNode = createNode(coeff, x_exp, y_exp, z_exp);

if (*header == NULL) {

*header = newNode;

} else {

Node* temp = *header;

while (temp->next != *header) {

temp = temp->next;

temp->next = newNode;

newNode->next = *header;

// Function to print the polynomial

void printPolynomial(Node* header) {

if (header == NULL) {

printf("Polynomial is empty.\n");

return;

Node* temp = header;

do {

printf("%d*x^%d*y^%d*z^%d", temp->coeff, temp->x_exp, temp->y_exp, temp->z_exp);

temp = temp->next;

if (temp != header) {

printf(" + ");

} while (temp != header);

printf("\n");

Rajiv Gandhi Institute of Technology 2024


61
Data Structures Lab BSCL305

// Function to evaluate the polynomial

int evaluatePolynomial(Node* header, int x, int y, int z) {

int result = 0;

Node* temp = header;

do {

int termValue = temp->coeff;

termValue *= pow(x, temp->x_exp);

termValue *= pow(y, temp->y_exp);

termValue *= pow(z, temp->z_exp);

result += termValue;

temp = temp->next;

} while (temp != header);

return result;

// Function to add two polynomials

Node* addPolynomials(Node* header1, Node* header2) {

Node* result = NULL;

Node* temp1 = header1;

Node* temp2 = header2;

do {

int found = 0;

Node* tempResult = result;

do {

if (tempResult && temp1->x_exp == tempResult->x_exp && temp1->y_exp ==


tempResult->y_exp && temp1->z_exp == tempResult->z_exp) {

tempResult->coeff += temp1->coeff;

found = 1;

break;

tempResult = tempResult ? tempResult->next : NULL;

Rajiv Gandhi Institute of Technology 2024


62
Data Structures Lab BSCL305

} while (tempResult != result);

if (!found) {

insertNode(&result, temp1->coeff, temp1->x_exp, temp1->y_exp, temp1->z_exp);

temp1 = temp1->next;

} while (temp1 != header1);

do {

int found = 0;

Node* tempResult = result;

do {

if (tempResult && temp2->x_exp == tempResult->x_exp && temp2->y_exp ==


tempResult->y_exp && temp2->z_exp == tempResult->z_exp) {

found = 1;

break;

tempResult = tempResult ? tempResult->next : NULL;

} while (tempResult != result);

if (!found) {

insertNode(&result, temp2->coeff, temp2->x_exp, temp2->y_exp, temp2->z_exp);

temp2 = temp2->next;

} while (temp2 != header2);

return result;

// Main function

int main() {

Rajiv Gandhi Institute of Technology 2024


63
Data Structures Lab BSCL305

Node* poly1 = NULL;

Node* poly2 = NULL;

// Add terms to polynomial 1

insertNode(&poly1, 6, 2, 2, 1);

insertNode(&poly1, -4, 0, 1, 5);

insertNode(&poly1, 3, 3, 1, 1);

insertNode(&poly1, 2, 1, 5, 1);

insertNode(&poly1, -2, 1, 1, 3);

// Add terms to polynomial 2 (example terms)

insertNode(&poly2, 2, 2, 2, 0);

insertNode(&poly2, -1, 0, 1, 4);

// Print polynomials

printf("Polynomial 1:\n");

printPolynomial(poly1);

printf("Polynomial 2:\n");

printPolynomial(poly2);

// Evaluate polynomial 1

int x = 1, y = 1, z = 1;

int evalResult = evaluatePolynomial(poly1, x, y, z);

printf("Evaluation of Polynomial 1 at x=%d, y=%d, z=%d: %d\n", x, y, z, evalResult);

// Add polynomials

Node* polySum = addPolynomials(poly1, poly2);

printf("Sum of Polynomial 1 and Polynomial 2:\n");

printPolynomial(polySum);

return 0;

Rajiv Gandhi Institute of Technology 2024


64
Data Structures Lab BSCL305

Output:

Polynomial 1:

6*x^2*y^2*z^1 + -4*x^0*y^1*z^5 + 3*x^3*y^1*z^1 + 2*x^1*y^5*z^1 + -2*x^1*y^1*z^3

Polynomial 2:

2*x^2*y^2*z^0 + -1*x^0*y^1*z^4

Evaluation of Polynomial 1 at x=1, y=1, z=1: 5

Sum of Polynomial 1 and Polynomial 2:

6*x^2*y^2*z^1 + -4*x^0*y^1*z^5 + 3*x^3*y^1*z^1 + 2*x^1*y^5*z^1 + -2*x^1*y^1*z^3 +


2*x^2*y^2*z^0 + -1*x^0*y^1*z^4

Rajiv Gandhi Institute of Technology 2024


65
Data Structures Lab BSCL305

10. Develop a menu driven Program in C for the following operations on Binary Search Tree (BST) of
Integers.

e. Create a BST of N Integers: 6, 9, 5, 2, 8, 15, 24, 14, 7, 8, 5, 2


f. Traverse the BST in In order, Preorder and Post Order
g. Search the BST for a given element (KEY) and report the appropriate message
h. Exit

#include <stdio.h>

#include <stdlib.h>

// Node structure for BST

typedef struct Node {

int data;

struct Node* left;

struct Node* right;

} Node;

// Function to create a new node

Node* createNode(int data) {

Node* newNode = (Node*)malloc(sizeof(Node));

newNode->data = data;

newNode->left = NULL;

newNode->right = NULL;

return newNode;

// Function to insert a new node into the BST

Node* insert(Node* root, int data) {

if (root == NULL) {

return createNode(data);

if (data < root->data) {

Rajiv Gandhi Institute of Technology 2024


66
Data Structures Lab BSCL305

root->left = insert(root->left, data);

} else if (data > root->data) {

root->right = insert(root->right, data);

return root;

// Function for In-order traversal

void inOrder(Node* root) {

if (root != NULL) {

inOrder(root->left);

printf("%d ", root->data);

inOrder(root->right);

// Function for Pre-order traversal

void preOrder(Node* root) {

if (root != NULL) {

printf("%d ", root->data);

preOrder(root->left);

preOrder(root->right);

// Function for Post-order traversal

void postOrder(Node* root) {

if (root != NULL) {

postOrder(root->left);

postOrder(root->right);

printf("%d ", root->data);

Rajiv Gandhi Institute of Technology 2024


67
Data Structures Lab BSCL305

// Function to search for a given element in the BST

Node* search(Node* root, int key) {

if (root == NULL || root->data == key) {

return root;

if (key < root->data) {

return search(root->left, key);

return search(root->right, key);

// Function to display menu and perform operations

void menu(Node* root) {

int choice, key;

while (1) {

printf("\nMenu:\n");

printf("1. In-order Traversal\n");

printf("2. Pre-order Traversal\n");

printf("3. Post-order Traversal\n");

printf("4. Search for an Element\n");

printf("5. Exit\n");

printf("Enter your choice: ");

scanf("%d", &choice);

switch (choice) {

case 1:

printf("In-order Traversal: ");

inOrder(root);

Rajiv Gandhi Institute of Technology 2024


68
Data Structures Lab BSCL305

printf("\n");

break;

case 2:

printf("Pre-order Traversal: ");

preOrder(root);

printf("\n");

break;

case 3:

printf("Post-order Traversal: ");

postOrder(root);

printf("\n");

break;

case 4:

printf("Enter element to search: ");

scanf("%d", &key);

if (search(root, key)) {

printf("Element %d found in the BST.\n", key);

} else {

printf("Element %d not found in the BST.\n", key);

break;

case 5:

printf("Exiting...\n");

return;

default:

printf("Invalid choice. Please try again.\n");

// Main function

Rajiv Gandhi Institute of Technology 2024


69
Data Structures Lab BSCL305

int main() {

Node* root = NULL;

int elements[] = {6, 9, 5, 2, 8, 15, 24, 14, 7, 8, 5, 2};

int n = sizeof(elements) / sizeof(elements[0]);

// Create the BST

for (int i = 0; i < n; i++) {

root = insert(root, elements[i]);

// Display menu and perform operations

menu(root);

return 0;

Output:

Menu:

1. In-order Traversal

2. Pre-order Traversal

3. Post-order Traversal

4. Search for an Element

5. Exit

Enter your choice: 1

In-order Traversal: 2 5 6 7 8 9 14 15 24

Menu:

1. In-order Traversal

2. Pre-order Traversal

3. Post-order Traversal

Rajiv Gandhi Institute of Technology 2024


70
Data Structures Lab BSCL305

4. Search for an Element

5. Exit

Enter your choice: 2

Pre-order Traversal: 6 5 2 9 8 7 15 14 24

Menu:

1. In-order Traversal

2. Pre-order Traversal

3. Post-order Traversal

4. Search for an Element

5. Exit

Enter your choice: 2

Pre-order Traversal: 6 5 2 9 8 7 15 14 24

Menu:

1. In-order Traversal

2. Pre-order Traversal

3. Post-order Traversal

4. Search for an Element

5. Exit

Enter your choice: 4

Enter element to search: 2

Element 2 found in the BST.

Menu:

1. In-order Traversal

2. Pre-order Traversal

3. Post-order Traversal

4. Search for an Element

5. Exit

Enter your choice: 5

Rajiv Gandhi Institute of Technology 2024


71
Data Structures Lab BSCL305

11. Develop a Program in C for the following operations on Graph(G) of Cities


c. Create a Graph of N cities using Adjacency Matrix.
d. Print all the nodes reachable from a given starting node in a digraph using DFS/BFS
method.

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

#define MAX_VERTICES 100

// Function to initialize the adjacency matrix


void initializeGraph(int graph[MAX_VERTICES][MAX_VERTICES], int n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
graph[i][j] = 0; // Initialize all edges to 0 (no edge)
}
}
}

// Function to add an edge to the graph


void addEdge(int graph[MAX_VERTICES][MAX_VERTICES], int u, int v) {
graph[u][v] = 1; // Directed edge from u to v
}

// Function to print the adjacency matrix


void printGraph(int graph[MAX_VERTICES][MAX_VERTICES], int n) {
printf("Adjacency Matrix:\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
printf("%d ", graph[i][j]);
}
printf("\n");
}
}

// Depth-First Search (DFS)


void DFS(int graph[MAX_VERTICES][MAX_VERTICES], int n, int start, bool visited[]) {
printf("%d ", start);
visited[start] = true;

for (int i = 0; i < n; i++) {


if (graph[start][i] && !visited[i]) {
DFS(graph, n, i, visited);
}
}

Rajiv Gandhi Institute of Technology 2024


72
Data Structures Lab BSCL305

// Breadth-First Search (BFS)


void BFS(int graph[MAX_VERTICES][MAX_VERTICES], int n, int start) {
bool visited[MAX_VERTICES] = { false };
int queue[MAX_VERTICES];
int front = 0, rear = 0;

visited[start] = true;
queue[rear++] = start;

while (front < rear) {


int node = queue[front++];
printf("%d ", node);

for (int i = 0; i < n; i++) {


if (graph[node][i] && !visited[i]) {
visited[i] = true;
queue[rear++] = i;
}
}
}
}

int main() {
int graph[MAX_VERTICES][MAX_VERTICES];
int n, e, u, v, start;
int choice;

printf("Enter the number of cities (vertices): ");


scanf("%d", &n);

// Initialize and create the graph


initializeGraph(graph, n);

printf("Enter the number of edges: ");


scanf("%d", &e);

printf("Enter the edges (u v) where u -> v:\n");


for (int i = 0; i < e; i++) {
scanf("%d %d", &u, &v);
addEdge(graph, u, v);
}

// Print the graph


printGraph(graph, n);

printf("\nChoose traversal method:\n");

Rajiv Gandhi Institute of Technology 2024


73
Data Structures Lab BSCL305

printf("1. DFS\n");
printf("2. BFS\n");
printf("Enter your choice: ");
scanf("%d", &choice);

printf("Enter starting node: ");


scanf("%d", &start);

bool visited[MAX_VERTICES] = { false };

switch (choice) {
case 1:
printf("DFS traversal starting from node %d:\n", start);
DFS(graph, n, start, visited);
printf("\n");
break;
case 2:
printf("BFS traversal starting from node %d:\n", start);
BFS(graph, n, start);
printf("\n");
break;
default:
printf("Invalid choice.\n");
}

return 0;
}

Output:

Enter the number of cities (vertices): 3


Enter the number of edges: 4
Enter the edges (u v) where u -> v:
02
01
12
10
Adjacency Matrix:
011
101
000

Choose traversal method:


1. DFS
2. BFS
Enter your choice: 1
Enter starting node: 0
DFS traversal starting from node 0:

Rajiv Gandhi Institute of Technology 2024


74
Data Structures Lab BSCL305

012

12. Given a File of N employee records with a set K of Keys (4-digit) which uniquely determine the
records in file F. Assume that file F is maintained in memory by a Hash Table (HT) of m memory

Rajiv Gandhi Institute of Technology 2024


75
Data Structures Lab BSCL305

locations with L as the set of memory addresses (2-digit) of locations in HT. Let the keys in K and
addresses in L are Integers. Develop a Program in C that uses Hash Function H: K →L as H(K)=K mod
m (remainder method), and implement hashing technique to map a given key K to the address space
L. Resolve the collision (if any) using linear probing.

#include <stdio.h>

#include <stdlib.h>

#define MAX_KEYS 100

#define TABLE_SIZE 10 // Size of the hash table

// Hash Table structure

typedef struct {

int key;

int isOccupied; // 1 if slot is occupied, 0 otherwise

} HashTable;

// Function to initialize the hash table

void initializeHashTable(HashTable ht[], int size) {

for (int i = 0; i < size; i++) {

ht[i].key = -1; // -1 indicates an empty slot

ht[i].isOccupied = 0;

// Hash function

int hashFunction(int key, int m) {

return key % m;

// Function to insert a key into the hash table

Rajiv Gandhi Institute of Technology 2024


76
Data Structures Lab BSCL305

void insert(HashTable ht[], int key, int size) {

int index = hashFunction(key, size);

int originalIndex = index;

int i = 0;

while (ht[index].isOccupied) {

if (ht[index].key == key) {

printf("Key %d already exists in the hash table.\n", key);

return;

i++;

index = (originalIndex + i) % size;

if (index == originalIndex) {

printf("Hash table is full, cannot insert key %d.\n", key);

return;

ht[index].key = key;

ht[index].isOccupied = 1;

printf("Key %d inserted at index %d.\n", key, index);

// Function to display the hash table

void displayHashTable(HashTable ht[], int size) {

printf("Hash Table:\n");

for (int i = 0; i < size; i++) {

if (ht[i].isOccupied) {

printf("Index %d: Key %d\n", i, ht[i].key);

} else {

printf("Index %d: Empty\n", i);

Rajiv Gandhi Institute of Technology 2024


77
Data Structures Lab BSCL305

int main() {

HashTable hashTable[TABLE_SIZE];

int keys[MAX_KEYS];

int n, key;

// Initialize hash table

initializeHashTable(hashTable, TABLE_SIZE);

printf("Enter the number of keys to insert: ");

scanf("%d", &n);

printf("Enter %d keys (4-digit integers):\n", n);

for (int i = 0; i < n; i++) {

scanf("%d", &keys[i]);

insert(hashTable, keys[i], TABLE_SIZE);

// Display the hash table

displayHashTable(hashTable, TABLE_SIZE);

return 0;

Output :

Enter the number of keys to insert: 4

Enter 4 keys (4-digit integers):

Rajiv Gandhi Institute of Technology 2024


78
Data Structures Lab BSCL305

1234

Key 1234 inserted at index 4.

3452

Key 3452 inserted at index 2.

2421

Key 2421 inserted at index 1.

4223

Key 4223 inserted at index 3.

Hash Table:

Index 0: Empty

Index 1: Key 2421

Index 2: Key 3452

Index 3: Key 4223

Index 4: Key 1234

Index 5: Empty

Index 6: Empty

Index 7: Empty

Index 8: Empty

Index 9: Empty

Rajiv Gandhi Institute of Technology 2024


79

You might also like