Data Structure Lab Manual 2
Data Structure Lab Manual 2
Data Structure Lab Manual 2
2022 scheme
Created By
Mr. Aayush Poudel.
Programs:
Program 1:
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>
struct Day {
char *name;
int date;
char *activity;
};
int main() {
int numDays = 7;
struct Day *calendar[numDays];
printf("Enter the details for the calendar:\n");
return 0;
}
Sample output:
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>
if (match) {
// Pattern found, copy the replacement
patternfound = 1; // Set patternfound to 1
for (int r = 0; r < repLen; r++) {
result[k] = rep[r];
k++;
}
i += patLen;
} else {
// No pattern match, copy the original character
result[k] = str[i];
i++;
k++;
}
}
if (!patternfound)
{
printf("Pattern not found in the main string. No replacements were made.\n");
}
else {
// Copy the result back to the original string
for (i = 0; i <= k; i++) {
str[i] = result[i];
}
}
}
//main
int main()
{
char mainStr[1000];
char pattern[100];
char replacement[100];
// Read the main string, pattern, and replacement from the user
readString(mainStr, "Enter the main string");
readString(pattern, "Enter the pattern to search for");
readString(replacement, "Enter the replacement string");
return 0;
}
Sample output 1:
Enter the main string: This is a test sentence with test pattern.
Enter the pattern to search for: test.
Enter the replacement string: sample.
Sample output 2:
Enter the main string: This is a test sentence with a pattern.
Enter the pattern to search for: sample.
Enter the replacement string: pattern.
Pattern not found in the main string. No replacements were made.
Modified String: This is a test sentence with a pattern.
Program 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 5
int st[MAX], top = -1, status = 0, count;
void push(int st[], int val);
int pop(int st[]);
int peek(int st[]);
void display(int st[]);
void palindrome(int st[]);
void main()
{
int val, option;
do {
printf("\nMenu");
printf("\n1.PUSH");
printf("\n2.POP");
printf("\n3.PEEK");
printf("\n4.DISPLAY");
printf("\n5.PALINDROME");
printf("\nEXIT");
printf("\nenter your option");
scanf("%d", &option);
switch (option)
{
case 1:
printf("\nenter number to push");
scanf("%d", &val);
push(st, val);
display(st);
break;
case 2:
val = pop(st);
if (val != -1)
printf("\ndeleted value %d", val);
display(st);
break;
case 3:
val = peek(st);
if (val != -1)
printf("top of stack:%d", val);
break;
case 4:
display(st);
break;
case 5:
palindrome(st);
break;
case 6:
exit(0);
break;
}
}
while (option != 6);
return;
}
void push(int st[], int val)
{
if (top == MAX - 1)
{
printf("\nSTACK OVERFLOW");
}
else
{
top++;
st[top] = val;
status++;
}
}
int pop(int st[])
{
int val;
if (top == -1)
{
printf("\nSTOCK UNDERFLOW");
return -1;
}
else
{
val = st[top];
top--;
status--;
return val;
}
}
void display(int st[])
{
int front,rear, i = front;
if (front == -1 && rear == -1)
printf("\nStack Overflow");
else
{
printf("\nthe stack contents are");
for (i = top; i >= 0; i--)
printf("\n%d", st[i]);
printf("\n");
}
}
int peek(int st[])
{
if (top == -1)
{
printf("\nStack Overflow");
return -1;
}
else
return (st[top]);
}
void palindrome(int st[])
{
int i, temp;
temp = status;
for (i = 0; i < temp; i++)
{
if (st[i] == pop(st))
count++;
}
if (temp == count)
printf("\nstack contents are palindrome");
else
printf("\nstack contents are not palindrome");
Sample OUTPUT:
Menu
1.PUSH
2.POP
3.PEEK
4.DISPLAY
5.PALINDROME
EXIT
enter your option1
enter number to push10
the stack contents are
10
Menu
1.PUSH
2.POP
3.PEEK
4.DISPLAY
5.PALINDROME
EXIT
enter your option1
enter number to push20
the stack contents are
20
10
Menu
1.PUSH
2.POP
3.PEEK
4.DISPLAY
5.PALINDROME
EXIT
enter your option1
enter number to push30
the stack contents are
30
20
10
Menu
1.PUSH
2.POP
3.PEEK
4.DISPLAY
5.PALINDROME
EXIT
enter your option2
deleted value 30
the stack contents are
20
10
Menu
1.PUSH
2.POP
3.PEEK
4.DISPLAY
5.PALINDROME
EXIT
enter your option3
top of stack:20
Menu
1.PUSH
2.POP
3.PEEK
4.DISPLAY
5.PALINDROME
EXIT
enter your option1
enter number to push20
the stack contents are
20
20
10
Menu
1.PUSH
2.POP
3.PEEK
4.DISPLAY
5.PALINDROME
EXIT
enter your option1
enter number to push10
the stack contents are
10
20
20
10
Menu
1.PUSH
2.POP
3.PEEK
4.DISPLAY
5.PALINDROME
EXIT
enter your option5
stack contents are palindrome
Program 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 <string.h>
if ((currentChar >= 'a' && currentChar <= 'z') || (currentChar >= '0' && currentChar <= '9')) {
postfix[postfixIdx++] = currentChar;
} else if (currentChar == '(') {
push(&operatorStack, currentChar);
} else if (currentChar == ')') {
while (!isEmpty(&operatorStack) && operatorStack.items[operatorStack.top] != '(') {
postfix[postfixIdx++] = pop(&operatorStack);
}
if (!isEmpty(&operatorStack) && operatorStack.items[operatorStack.top] == '(') {
pop(&operatorStack);
}
} else {
while(!
isEmpty(&operatorStack)&&getPrecedence(currentChar)<=getPrecedence(operatorStack.items[ope
ratorStack.top]))
{
postfix[postfixIdx++] = pop(&operatorStack);
}
push(&operatorStack, currentChar);
}
}
while (!isEmpty(&operatorStack)) {
postfix[postfixIdx++] = pop(&operatorStack);
}
postfix[postfixIdx] = '\0';
}
//main
int main() {
char infixExpression[100];
char postfixExpression[MAX_OUTPUT_SIZE];
printf("Enter an infix expression: ");
scanf("%s", infixExpression);
infixToPostfix(infixExpression, postfixExpression);
printf("Postfix expression: %s\n", postfixExpression);
return 0;
}
Sample output
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int i = 0;
while (postfix[i] != '\0') {
char currentChar = postfix[i];
if (isdigit(currentChar)) {
push(&operandStack, currentChar - '0');
} else {
int operand2 = pop(&operandStack);
int operand1 = pop(&operandStack);
switch (currentChar) {
case '+':
push(&operandStack, operand1 + operand2);
break;
case '-':
push(&operandStack, operand1 - operand2);
break;
case '*':
push(&operandStack, operand1 * operand2);
break;
case '/':
push(&operandStack, operand1 / operand2);
break;
case '%':
push(&operandStack, operand1 % operand2);
break;
}
}
i++;
}
return pop(&operandStack);
}
//main
int main() {
char postfixExpression[100];
return 0;
}
Sample output :
#include <stdio.h>
return 0;
}
Sample output
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.
#include <stdio.h>
#include <stdlib.h>
char queue[MAX];
int front = -1, rear = -1;
switch (choice) {
case 1:
printf("Enter the element to insert: ");
scanf(" %c", &element);
insertElement(element);
break;
case 2:
deleteElement();
break;
case 3:
if (isFull()) {
printf("Queue is full (Overflow)!\n");
} else if (isEmpty()) {
printf("Queue is empty (Underflow)!\n");
} else {
printf("Queue is neither empty nor full.\n");
}
break;
case 4:
displayQueue();
break;
case 5:
exit(0);
default:
printf("Invalid choice. Please try again.\n");
}
}
return 0;
}
Sample output
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
if (newStudent == NULL) {
printf("Memory allocation failed.\n");
exit(1);
}
newStudent->next = NULL;
return newStudent;
}
// Function to display the linked list and count the number of nodes
void displayAndCount() {
struct Student* current = head;
int count = 0;
if (current == NULL) {
printf("The list is empty.\n");
return;
}
printf("Student List:\n");
while (current != NULL)
{
printf("USN: %s\nName: %s\nProgramme: %s\nSemester: %d\nPhone Number: %s\n\n",
current->usn, current->name, current->programme, current->sem, current->phNo);
current = current->next;
count++;
}
if (head == NULL) {
head = newStudent;
} else {
struct Student* current = head;
while (current->next != NULL) {
current = current->next;
}
current->next = newStudent;
}
if (head->next == NULL) {
free(head);
head = NULL;
printf("Student deleted from the end of the list.\n");
return;
}
free(current->next);
current->next = NULL;
printf("Student deleted from the end of the list.\n");
}
int main() {
int choice;
while (1) {
printf("\nStudent Data Menu:\n");
printf("1. Create a student list by using front insertion\n");
printf("2. Display the list and count the number of students\n");
printf("3. Insert a student at the end of the list\n");
printf("4. Delete a student from the front of the list\n");
printf("5. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
insertFront();
break;
case 2:
displayAndCount();
break;
case 3:
insertEnd();
break;
case 4:
deleteFront();
break;
case 5:
exitProgram();
break;
default:
printf("Invalid choice. Please try again.\n");
}
}
return 0;
}
Sample output
USN: 1234
Name: Alice
Programme: Engineering
Semester: 3
Phone Number: 123-456-7890
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Global pointers for the head and tail of the doubly linked list
struct Employee* head = NULL;
struct Employee* tail = NULL;
if (newEmployee == NULL) {
printf("Memory allocation failed.\n");
exit(1);
}
newEmployee->next = NULL;
newEmployee->prev = NULL;
return newEmployee;
}
if (head == NULL) {
head = tail = newEmployee;
} else {
tail->next = newEmployee;
newEmployee->prev = tail;
tail = newEmployee;
}
printf("Employee inserted at the end of the list.\n");
}
// Function to display the doubly linked list and count the number of nodes
void displayAndCount() {
struct Employee* current = head;
int count = 0;
if (current == NULL) {
printf("The list is empty.\n");
return;
}
printf("Employee List:\n");
while (current != NULL) {
printf("SSN: %s\nName: %s\nDepartment: %s\nDesignation: %s\nSalary: %.2f\nPhone
Number: %s\n\n", current->ssn, current->name, current->dept, current->designation, current->sal,
current->phNo);
current = current->next;
count++;
}
if (head == NULL) {
head = tail = newEmployee;
} else {
newEmployee->next = head;
head->prev = newEmployee;
head = newEmployee;
}
printf("Employee inserted at the front of the list.\n");
}
if (head == tail) {
free(head);
head = tail = NULL;
} else {
struct Employee* temp = tail;
tail = tail->prev;
tail->next = NULL;
free(temp);
}
printf("Employee deleted from the end of the list.\n");
}
if (head == tail) {
free(head);
head = tail = NULL;
} else {
struct Employee* temp = head;
head = head->next;
head->prev = NULL;
free(temp);
}
printf("Employee deleted from the front of the list.\n");
}
switch (choice) {
case 1:
insertFront();
break;
case 2:
insertEnd();
break;
case 3:
deleteFront();
break;
case 4:
deleteEnd();
break;
case 5:
return;
default:
printf("Invalid choice. Please try again.\n");
}
}
}
switch (choice) {
case 1:
insertEnd();
break;
case 2:
displayAndCount();
break;
case 3:
insertEnd();
break;
case 4:
insertFront();
break;
case 5:
dequeueDemo();
break;
case 6:
exitProgram();
break;
default:
printf("Invalid choice. Please try again.\n");
}
}
return 0;
}
Sample output
SSN: 54321
Name: Jane Smith
Department: HR
Designation: Manager
Salary: 75000.00
Phone Number: 555-987-6543
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) = 6x2y2z-4yz5+3x' yz+2xy5z-2xyz'
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
A
Represent and Evaluate a Polynomial P(x,y,z) = 6x2y2z-4yz5+3x' yz+2xy5z-2xyz'
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
if (current == NULL) {
// The polynomial is empty, so insert the term as the first term
polynomial->link = term;
term->next = term;
polynomial->num_terms++;
} else {
// Find the appropriate position for insertion
while (current->next != polynomial->link) {
current = current->next;
}
// Insert the term at the end and update the circular link
current->next = term;
term->next = polynomial->link;
polynomial->num_terms++;
}
}
// Function to display a polynomial
void displayPolynomial(struct Header* polynomial, const char* variable) {
if (polynomial->num_terms == 0) {
printf("The polynomial is empty.\n");
return;
}
if (current->exponent_x > 0) {
printf("%c^%d", variable[0], current->exponent_x);
}
if (current->exponent_y > 0) {
printf("%c^%d", variable[1], current->exponent_y);
}
if (current->exponent_z > 0) {
printf("%c^%d", variable[2], current->exponent_z);
}
current = current->next;
} while (current != polynomial->link);
printf("\n");
}
// Function to evaluate a polynomial for given values of x, y, and z
int evaluatePolynomial(struct Header* polynomial, int x, int y, int z) {
int result = 0;
struct Term* current = polynomial->link;
do {
int termValue = current->coefficient * pow(x, current->exponent_x) * pow(y, current-
>exponent_y) * pow(z, current->exponent_z);
result += termValue;
current = current->next;
} while (current != polynomial->link);
return result;
}
//main
int main() {
struct Header polynomial;
polynomial.num_terms = 0;
polynomial.link = NULL;
return 0;
}
Sample output
Find the sum of two polynomials POLY1(x,y,z) and POLY2(x,y,z) and store the result in
POLYSUM(x,y,z)
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
insertTerm(&poly2, term2a);
insertTerm(&poly2, term2b);
insertTerm(&poly2, term2c);
Sample output
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 Inorder, Preorder and Post Order
c. Search the BST for a given element (KEY) and report the appropriate message
d. Exit
#include <stdio.h>
#include <stdlib.h>
return root;
}
int choice;
int key;
int exists;
while (1) {
printf("\nBinary Search Tree Menu:\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: ");
inorderTraversal(root);
printf("\n");
break;
case 2:
printf("Pre-order Traversal: ");
preorderTraversal(root);
printf("\n");
break;
case 3:
printf("Post-order Traversal: ");
postorderTraversal(root);
printf("\n");
break;
case 4:
printf("Enter the element to search: ");
scanf("%d", &key);
exists = keyExists(root, key);
displaySearchResult(key, exists);
break;
case 5:
exitProgram(root);
break;
default:
printf("Invalid choice. Please try again.\n");
}
}
return 0;
}
Sample output
Program 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
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
// Define the maximum number of cities (you can adjust this as needed)
#define MAX_CITIES 100
int queue[MAX_CITIES];
int front = 0, rear = 0;
queue[rear++] = start;
initializeGraph(n);
bfs(startCity, n);
return 0;
}
Sample output
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 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>
// Function to insert an employee record into the hash table using linear probing
void insertEmployee(struct Employee employee, int m) {
int key = employee.key;
int address = hash(key, m);
hashTable[address].key = key;
hashTable[address].address = address;
printf("Enter the number of memory locations in the hash table (m): ");
scanf("%d", &m);
initializeHashTable(m);
return 0;
}
Sample output