Laboratory Component: Data Structures Laboratory (BCSL305) : Department of Computer Science and Engineering
Laboratory Component: Data Structures Laboratory (BCSL305) : Department of Computer Science and Engineering
Laboratory Component: Data Structures Laboratory (BCSL305) : Department of Computer Science and Engineering
)
Bapuji Institute of Engineering and Technology
Affiliated to Visvesvaraya Technological University, Belgavi, Accredited by NBA and NAAC with 'A' grade,
Recognized by UGC under 2(F) and 12(B)
Ⅲ Semester
Laboratory Component:
DATA STRUCTURES LABORATORY
[BCSL305]
Prepared by:
Dr. Naveen KUmar K R
Associate Professor
Dept. of CSE
BIET
Vision
Mission
1. Adapting best teaching and learning techniques that cultivates Questioning and
Reasoning culture among the students.
2. Creating collaborative learning environment that ignites the critical thinking in
students and leading to the innovation.
3. Establishing Industry Institute relationship to bridge the skill gap and make them
industry ready and relevant.
4. Mentoring students to be socially responsible by inculcating ethical and moral values.
1. To apply skills acquired in the discipline of Computer Science and Engineering for
solving societal and industrial problems with apt technology intervention.
2. To continue their career in industry/academia or to pursue higher studies and
research.
3. To become successful entrepreneurs, innovators to design and develop software
products and services that meets the societal, technical and business challenges.
4. To work in the diversified environment by acquiring leadership qualities with effective
communication skills accompanied by professional and ethical values.
1. Analyze and develop solutions for problems that are complex in nature by applying the
knowledge acquired from the core subjects of this program.
2. Ability to develop Secure, Scalable, Resilient and distributed applications for industry
and societal requirements.
3. Ability to learn and apply the concepts and construct of emerging technologies like
Artificial Intelligence, Machine learning, Deep learning, Big Data Analytics, IoT, Cloud
Computing, etc for any real time problems.
INDEX
LIST OF SOME BASIC UNIX COMMANDS:................................................................................. 1
CYGWIN................................................................................................................................................. 3
Vim.................................................................................................................................................... 4
3. IMPLEMENTATION OF STACK................................................................................................. 15
5. STACK APPLICATIONS............................................................................................................... 28
*, /, %, ^......................................................................................................................................... 28
9. POLYNOMIAL OPERATIONS.....................................................................................................65
11.OPERATIONS ON GRAPH..........................................................................................................81
12.HASHING........................................................................................................................................87
Laboratory Outcomes:
2. Demonstrate the working nature of different types of data structures and their
applications
3. Use appropriate searching and sorting algorithms for the give scenario.
4. Apply the appropriate data structure for solving real world problems
LIST OF SOME BASIC UNIX COMMANDS:
8. touch: Create an empty file or update the access and modification times of a file
- `touch <filename>`
2. Development and Testing: CSE students often need to develop and test
software across different platforms. With Cygwin, they can write and test code
that will ultimately run on Unix-based systems without needing to switch
between operating systems.
4. Compatibility: Some software tools and libraries are primarily developed for
Unix-like systems and may not have native Windows versions. Cygwin allows
students to use these tools and libraries on their Windows machines without
needing to set up a separate Unix environment.
Vim
Vim is a highly configurable text editor built to enable efficient text editing. It's
a descendant of the vi editor, with additional features and improvements. Here
are some key aspects and features of Vim:
1. Modal Editing: Vim uses modes for different functionalities. The most
commonly used modes are:
5. Split Windows: Vim allows splitting the editing window into multiple panes,
enabling users to view and edit multiple files simultaneously.
6. Built-in Tools: Vim includes built-in tools for tasks like searching and
replacing text, spell checking, and navigating through large files.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Main function
int main() {
Day* week = create();
read(week);
display(week);
free(week);
return 0;
}
OUTPUT:
**Input:** **Output:**
1. The program begins with the inclusion of necessary header files. `stdio.h` for standard
input/output and `stdlib.h` for dynamic memory allocation functions like `malloc()`.
2. A `typedef struct` is declared to define a new data type `Day`. This struct has three fields -
`name` (a pointer to char), `date` (an integer), and `activity` (another pointer to char). Here,
`name` and `activity` are pointers, meaning they can hold the address of a dynamically
allocated memory.
4. `void read(Day* week)` is a function that takes the pointer to the `Day` array as an
argument. It reads data from the console for each `Day` in the `week`. For each `Day`, it
reads the `name`, `date`, and `activity`. For `name` and `activity`, it first reads the input
into a buffer, then dynamically allocates just enough memory to copy the input from the
buffer to the `Day` fields.
5. `void display(Day* week)` takes the pointer to the `Day` array as an argument and displays
the information of each `Day` in the `week`.
6. In the `main` function, `create` is first called to create a `week` array. The `read` function
is then called to read data for each `Day` in the `week`. The `display` function is finally called
to display the information of each `Day`.
7. `free(week)` is called to clean up the dynamically allocated memory for the `week`.
However, this does not free the dynamically allocated memory for each `Day`'s `name` and
`activity`. To fully free all dynamically allocated memory, you should iterate over each `Day`
in the `week` and `free` the `name` and `activity` before `freeing` the `week` itself.
The program introduces the concept of dynamic memory allocation, how to read input into
dynamically allocated memory, and how to manipulate and display the data held in this
dynamically allocated memory. Remember to always free dynamically allocated memory
when you're done with it to prevent memory leaks.
2.PATTERN MATCHING OPERATION.
Support the program with functions for each of the above operations. Don't
use Built-in functions.
#include <stdio.h>
#include <stdlib.h>
int main() {
char STR[100], PAT[20], REP[20];
printf("Enter main string (STR): ");
fgets(STR, sizeof(STR), stdin);
printf("Enter pattern string (PAT): ");
fgets(PAT, sizeof(PAT), stdin);
printf("Enter replace string (REP): ");
fgets(REP, sizeof(REP), stdin);
return 0;
}
OUTPUT:
**Input:**
**Output:**
---
Example where the pattern does not exist in the main string:
**Input:**
**Output:**
1. The program first includes the necessary header files, `stdio.h` for standard input/output
and `stdlib.h` for dynamic memory allocation functions like `malloc()`.
a. `myStrLen`: This function calculates the length of a string by iterating through the
characters until it finds the null terminator.
b. `myStrCpy`: This function copies the contents of one string to another by iterating
through the characters and copying them one by one.
c. `myStrCat`: This function concatenates the content of two strings by first finding the end
of the first string and then copying the content of the second string to the end of the first
string.
3. The `strReplace` function takes the main string `STR`, pattern string `PAT`, and replaces
string `REP` as input. It iterates through the main string and attempts to find the pattern
string. If the pattern is found, it dynamically allocates memory to create a new modified
string by copying the content before the pattern, the replacement string, and the content after
the pattern. It then copies this modified string back to the main string. If the pattern is found,
it returns 1; otherwise, it returns 0.
4. In the `main` function, the user is prompted to input the main string, pattern string, and
replacement string. Then, the `strReplace` function is called to perform the find-and-replace
operation. If the pattern is not found, a message is printed to inform the user. If the pattern is
found and replaced, the modified main string is printed.
5. Remember that the code assumes that the user enters the main string, pattern, and
replacement without any leading or trailing whitespaces.
This program provides a basic example of pattern matching and string manipulation in C
without using built-in string functions. It showcases the use of pointers, memory allocation,
and string manipulation techniques.
3. IMPLEMENTATION OF STACK.
#include <stdio.h>
#define MAX 10
#define TRUE 1
#define FALSE 0
int stack[MAX];
int top = -1;
int isFull() {
return (top == MAX - 1);
}
int isEmpty() {
return (top == -1);
}
int pop() {
if (isEmpty()) {
printf("Stack Underflow!\n");
return -1; // Return -1 indicating stack is empty
} else {
return stack[top--];
}
}
int checkPalindrome() {
int i;
for (i = 0; i <= top / 2; i++) {
if (stack[i] != stack[top - i]) {
return FALSE;
}
}
return TRUE;
}
void displayStack() {
if (isEmpty()) {
printf("Stack is empty!\n");
} else {
printf("Stack elements are:\n");
for (int i = top; i >= 0; i--) {
printf("%d\n", stack[i]);
}
}
}
int main() {
int choice, value;
printf("Stack Operations:\n");
while (1) {
printf("1. Push an element onto stack\n");
printf("2. Pop an element from stack\n");
printf("3. Check if stack contents are palindrome\n");
printf("4. Display stack status (Overflow or Underflow)\n");
printf("5. Display all elements of stack\n");
printf("6. Exit\n");
printf("Enter your choice (1-6): ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter integer to push: ");
scanf("%d", &value);
push(value);
break;
case 2:
value = pop();
if (value != -1) {
printf("Popped element: %d\n", value);
}
break;
case 3:
if (checkPalindrome()) {
printf("Stack contents are a palindrome.\n");
} else {
printf("Stack contents are not a palindrome.\n");
}
break;
case 4:
if (isFull()) {
printf("Stack Overflow!\n");
} else if (isEmpty()) {
printf("Stack Underflow!\n");
} else {
printf("Stack is neither full nor empty.\n");
}
break;
case 5:
displayStack();
break;
case 6:
printf("Exiting program.\n");
return 0;
default:
printf("Invalid choice, please try again.\n");
}
printf("\n");
}
return 0;
}
OUTPUT:
Stack Operations:
1. Push an element onto stack
2. Pop an element from stack
3. Check if stack contents are palindrome
4. Display stack status (Overflow or Underflow)
5. Display all elements of stack
6. Exit
Enter your choice (1-6): 1
Enter integer to push: 10
10 pushed to stack.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
char stack[MAX];
int top = -1;
char pop() {
if (top == -1) {
printf("Stack Underflow\n");
return -1;
} else {
return stack[top--];
}
}
int main() {
char infix[MAX], postfix[MAX];
printf("Enter an infix expression: ");
gets(infix);
infixToPostfix(infix, postfix);
printf("Postfix expression: %s\n", postfix);
return 0;
}
Output:
#include <stdio.h>
#include <string.h>
#include <math.h>
#define MAX 10
int pop() {
if(top < 0) {
printf("Stack Underflow\n");
return 0;
}
else {
return stack[top--];
}
}
int is_operator(char c) {
switch(c) {
case '+':
case '-':
case '*':
case '/':
case '%':
case '^': return 1;
default: return 0;
}
}
else if(is_operator(c)) {
op2 = pop();
op1 = pop();
switch(c) {
case '+': push(op1 + op2); break;
case '-': push(op1 - op2); break;
case '*': push(op1 * op2); break;
case '/':
if(op2 == 0) {
printf("Error: Division by zero is not allowed.\n");
return -1;
}
else {
push(op1 / op2);
}
break;
case '%':
if(op2 == 0) {
printf("Error: Modulus by zero is not allowed.\n");
return -1;
}
else {
push((int)fmod(op1, op2));
}
break;
case '^': push((int)pow(op1, op2)); break;
}
}
}
return pop();
}
int main() {
char postfix[MAX];
int result;
result = evaluate_postfix(postfix);
if(result != -1)
printf("Result: %d\n", result);
return 0;
}
OUTPUT:
1. Stack Implementation: The program uses an array-based stack to store operands during
evaluation.
2. push and pop Functions: These functions handle adding and removing elements from
the stack.
3. evaluateSuffix Function:
○ It iterates through the expression character by character.
○ If a digit is encountered, it pushes it onto the stack as an operand.
○ If an operator is encountered, it pops the top two operands, performs the
operation, and pushes the result back onto the stack.
4. main Function:
○ It prompts the user to enter a suffix expression.
○ It calls evaluateSuffix to evaluate the expression.
○ It prints the final result.
b. Solving Tower of Hanoi problem with n disks
#include <stdio.h>
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: 3
#include <stdio.h>
#include <stdlib.h>
#define MAX_QUEUE_SIZE 5
char queue[MAX_QUEUE_SIZE];
int front = 0, rear = 0;
void showMenu() {
printf("\nMenu:\n");
printf("1. Insert an Element\n");
printf("2. Delete an Element\n");
printf("3. Demonstrate Overflow\n");
printf("4. Demonstrate Underflow\n");
printf("5. Display the status\n");
printf("6. Exit\n");
printf("Enter your choice: ");
}
int getUserChoice() {
int choice;
scanf("%d", &choice);
return choice;
}
if(front == 0){
rear = MAX_QUEUE_SIZE - 1;
} else{
rear = front - 1;
}
}
if (front == rear) {
queueFull();
return;
}
queue[rear] = item;
}
getchar();
switch (choice) {
case 1: {
printf("Enter the element to insert: ");
item = getchar();
addq(item);
}
break;
case 2: {
item = deleteq();
if (item != '\0') {
printf("Deleted element: %c\n", item);
}
}
break;
case 3: {
printf("Demonstrating Overflow...\n");
for (char ch = 'A'; ch <= 'F'; ch++) {
addq(ch);
}
displayStatus();
}
break;
case 4: {
printf("Demonstrating Underflow...\n");
for (int i = 0; i < MAX_QUEUE_SIZE; i++) {
deleteq();
}
displayStatus();
}
break;
case 5: {
printf("Displaying the status of Circular QUEUE:\n");
displayStatus();
}
break;
case 6:
printf("Exiting...\n");
break;
default:
printf("Invalid choice!\n");
}
}
int main() {
int choice;
do {
showMenu();
choice = getUserChoice();
processChoice(choice);
} while (choice != 6);
return 0;
}
OUTPUT:
#include <stdio.h>
#include <stdlib.h>
StudentPointer first;
void showMenu() {
printf("\n****** Menu ******\n");
printf("\n1. Insert N Studs at Front\n");
printf("2. Insert at Front\n");
printf("3. Insert at End\n");
printf("4. Delete from Front\n");
printf("5. Delete from End\n");
printf("6. Display\n");
printf("7. Exit\n");
printf("\nEnter your choice: ");
}
int getUserChoice() {
int choice;
scanf("%d", &choice);
return choice;
}
return newStudent;
}
if (newNode == NULL) {
printf("Memory allocation failed!\n");
exit(1); // Exit the program if memory allocation fails
}
newNode->data = data;
newNode->next = NULL;
return newNode;
}
if (first == NULL) {
first = newNode;
return;
}
last->next = newNode;
}
if (first->next == NULL) {
free(first);
first = NULL;
return;
}
free(second_last->next);
second_last->next = NULL;
}
switch (choice) {
case 1: {
printf("Enter the number of students: ");
scanf("%d", &n);
for (i = 0; i < n; i++) {
newStudent = readStudentData();
newStudentNode = getNode(newStudent);
insertFront(newStudentNode);
}
}
break;
case 2: {
newStudent = readStudentData();
newStudentNode = getNode(newStudent);
insertFront(newStudentNode);
}
break;
case 3: {
newStudent = readStudentData();
newStudentNode = getNode(newStudent);
insertEnd(newStudentNode);
}
break;
case 4: {
deleteFront();
}
break;
case 5: {
deleteEnd();
}
break;
case 6: {
display();
}
break;
case 7:
printf("Exiting...\n");
break;
default:
printf("Invalid choice!\n");
}
}
int main() {
int choice;
do {
showMenu();
choice = getUserChoice();
processChoice(choice);
} while (choice != 7);
return 0;
}
OUTPUT:
1. Insert at Front
2. Insert at End
5. Display
6. Exit
1. Insert at Front
2. Insert at End
5. Display
6. Exit
1. Insert at Front
2. Insert at End
3. Delete from Front
5. Display
6. Exit
1. Insert at Front
2. Insert at End
5. Display
6. Exit
USN: 333, Name: Kate, Programme: ISE, Semester: 7, Phone No: 33333
USN: 222, Name: Jack, Programme: CSE, Semester: 5, Phone No: 22222
USN: 111, Name: John, Programme: CSE, Semester: 3, Phone No: 11111
Total nodes: 3
1. Insert at Front
2. Insert at End
5. Display
6. Exit
1. Insert at Front
2. Insert at End
5. Display
6. Exit
1. Insert at Front
2. Insert at End
5. Display
6. Exit
1. Insert at Front
2. Insert at End
5. Display
6. Exit
USN: 333, Name: Kate, Programme: ISE, Semester: 7, Phone No: 33333
USN: 222, Name: Jack, Programme: CSE, Semester: 5, Phone No: 22222
USN: 111, Name: John, Programme: CSE, Semester: 3, Phone No: 11111
USN: 444, Name: Kathy, Programme: ECE, Semester: 2, Phone No: 44444
USN: 555, Name: Robert, Programme: ECE, Semester: 4, Phone No: 55555
USN: 666, Name: David, Programme: EEE, Semester: 6, Phone No: 66666
Total nodes: 6
1. Insert at Front
2. Insert at End
5. Display
6. Exit
1. Insert at Front
2. Insert at End
5. Display
6. Exit
1. Insert at Front
2. Insert at End
5. Display
6. Exit
USN: 222, Name: Jack, Programme: CSE, Semester: 5, Phone No: 22222
USN: 111, Name: John, Programme: CSE, Semester: 3, Phone No: 11111
USN: 444, Name: Kathy, Programme: ECE, Semester: 2, Phone No: 44444
USN: 555, Name: Robert, Programme: ECE, Semester: 4, Phone No: 55555
USN: 666, Name: David, Programme: EEE, Semester: 6, Phone No: 66666
USN: 666, Name: David, Programme: EEE, Semester: 6, Phone No: 66666
Total nodes: 6
1. Insert at Front
2. Insert at End
5. Display
6. Exit
1. Insert at Front
2. Insert at End
5. Display
6. Exit
USN: 111, Name: John, Programme: CSE, Semester: 3, Phone No: 11111
USN: 444, Name: Kathy, Programme: ECE, Semester: 2, Phone No: 44444
USN: 555, Name: Robert, Programme: ECE, Semester: 4, Phone No: 55555
USN: 666, Name: David, Programme: EEE, Semester: 6, Phone No: 66666
USN: 666, Name: David, Programme: EEE, Semester: 6, Phone No: 66666
Total nodes: 5
1. Insert at Front
2. Insert at End
6. Exit
1. Insert at Front
2. Insert at End
5. Display
6. Exit
USN: 111, Name: John, Programme: CSE, Semester: 3, Phone No: 11111
USN: 444, Name: Kathy, Programme: ECE, Semester: 2, Phone No: 44444
USN: 555, Name: Robert, Programme: ECE, Semester: 4, Phone No: 55555
USN: 666, Name: David, Programme: EEE, Semester: 6, Phone No: 66666
Total nodes: 4
1. Insert at Front
2. Insert at End
5. Display
6. Exit
This code is a simple linked list implementation in C, with functions to perform basic
operations such as insertion, deletion, and display. Here's a breakdown of the code:
1. The first section of the code includes necessary header files and defines a structure called
"node" that represents a node in the linked list. The structure contains five members:
* usn (username)
* name (name)
* sem (semester)
* countNodes: This function takes a pointer to the head node of the list as an argument
and returns the number of nodes in the list. It does this by iterating through the list and
incrementing a count variable for each node.
* createNode: This function creates a new node and returns a pointer to it. It prompts
the user to enter the values for the five members of the node, and then allocates memory for
the node using malloc.
* insertFront: This function inserts a new node at the beginning of the list. It creates a
new node using createNode, sets its next pointer to the current head of the list, and then sets
the head of the list to the new node.
* insertEnd: This function inserts a new node at the end of the list. It creates a new
node using createNode, and then iterates through the list to find the last node. It sets the last
node's next pointer to the new node, and then sets the new node's next pointer to NULL.
* deleteFront: This function deletes the node at the beginning of the list. It sets the
head of the list to the second node, frees the memory allocated to the first node, and then
prints a message indicating that the list is empty if the list is now empty.
* deleteEnd: This function deletes the node at the end of the list. It iterates through the
list to find the second-to-last node, sets its next pointer to NULL, frees the memory allocated
to the last node, and then prints a message indicating that the list is empty if the list is now
empty.
3. The final section of the code defines a driver function called main, which is the entry point
for the program. It uses a do-while loop to repeatedly prompt the user to choose an operation
to perform on the list. The choices are:
* 1: Insert at front
* 2: Insert at end
* 5: Display
* 6: Exit
The main function calls the appropriate function based on the user's choice, and then
continues to the next iteration of the loop. If the user chooses to exit, the program terminates.
8. OPERATIONS ON DOUBLY LINKED LIST (DLL)
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
Updated on: Feb 23, 2024
#include <stdio.h>
#include <stdlib.h>
typedef struct {
char socialSecurityNumber[15];
char fullName[50];
char department[30];
char jobDesignation[30];
float salary;
char phoneNumber[15];
} EmployeeInfo;
EmployeePointer head;
void showMenu() {
printf("\n1. Create DLL of N Employees (End Insertion)\n");
printf("2. Display DLL and Count Nodes\n");
printf("3. Insert at End\n");
printf("4. Delete at End\n");
printf("5. Insert at Front\n");
printf("6. Delete at Front\n");
printf("7. Exit\n");
printf("Enter your choice: ");
}
int getUserChoice() {
int choice;
scanf("%d", &choice);
return choice;
}
return newEmployee;
}
if (newNode != NULL) {
// Initialize the data
newNode->data = data;
// Make it circular
newNode->llink = newNode;
newNode->rlink = newNode;
}else{
printf("Memory allocation failed\n");
exit(EXIT_FAILURE);
}
return newNode;
}
void displayList(void) {
EmployeePointer current = head->rlink; // Start from the first node
printf("\nDoubly Linked List:\n");
while (current != head) {
printf("SSN: %s, Name: %s, Dept: %s, Designation: %s, Sal: %.2f,
PhNo: %s\n",
current->data.socialSecurityNumber, current->data.fullName,
current->data.department,
current->data.jobDesignation, current->data.salary,
current->data.phoneNumber);
current = current->rlink; // Move to the next node
}
}
switch (choice) {
case 1: {
printf("Enter the number of employees: ");
scanf("%d", &n);
for (i = 0; i < n; i++) {
newEmployee = readEmployeeData();
newEmployeeNode = getNode(newEmployee);
dinsert(head, newEmployeeNode);
}
}
break;
case 2: {
displayList();
}
break;
case 3: {
newEmployee = readEmployeeData();
newEmployeeNode = getNode(newEmployee);
dinsert(head->llink, newEmployeeNode);
}
break;
case 4: {
ddelete(head, head->rlink);
}
break;
case 5: {
newEmployee = readEmployeeData();
newEmployeeNode = getNode(newEmployee);
dinsert(head, newEmployeeNode);
}
break;
case 6: {
ddelete(head, head->llink);
}
break;
case 7:
printf("Exiting...\n");
break;
default:
printf("Invalid choice!\n");
}
}
int main() {
EmployeeInfo temp;
int choice;
head = getNode(temp);
do {
showMenu();
choice = getUserChoice();
processChoice(choice);
} while (choice != 7);
return 0;
}
OUTPUT:
1. Create DLL of N Employees (End Insertion)
2. Display DLL and Count Nodes
3. Insert at End
4. Delete at End
5. Insert at Front
6. Delete at Front
7. Exit
SSN: 222, Name: Anthony , Dept: ISE , Designation: Professor, Sal: 222222.00, PhNo:
978456123
SSN: 111, Name: James , Dept: CSE , Designation: Associate Professor, Sal: 111111.00, PhNo:
987456123
SSN: 222, Name: Anthony , Dept: ISE , Designation: Professor, Sal: 222222.00, PhNo:
978456123
SSN: 111, Name: James , Dept: CSE , Designation: Associate Professor, Sal: 111111.00, PhNo:
987456123
SSN: 444, Name: Daniel , Dept: ME, Designation: Lecture, Sal: 44444.00, PhNo: 947856123
1. Create DLL of N Employees (End Insertion)
2. Display DLL and Count Nodes
3. Insert at End
4. Delete at End
5. Insert at Front
6. Delete at Front
7. Exit
SSN: 333, Name: Jacob , Dept: CSE , Designation: Assistant Professor, Sal: 333333.00, PhNo:
974856123
SSN: 222, Name: Anthony , Dept: ISE , Designation: Professor, Sal: 222222.00, PhNo:
978456123
SSN: 111, Name: James , Dept: CSE , Designation: Associate Professor, Sal: 111111.00, PhNo:
987456123
SSN: 444, Name: Daniel , Dept: ME, Designation: Lecture, Sal: 44444.00, PhNo: 947856123
SSN: 222, Name: Anthony , Dept: ISE , Designation: Professor, Sal: 222222.00, PhNo:
978456123
SSN: 111, Name: James , Dept: CSE , Designation: Associate Professor, Sal: 111111.00, PhNo:
987456123
SSN: 444, Name: Daniel , Dept: ME, Designation: Lecture, Sal: 44444.00, PhNo: 947856123
Exiting...
9. POLYNOMIAL OPERATIONS
Develop a Program in C for the following operations on Singly Circular
Linked List (SCLL) with header nodes
#include <stdio.h>
#include <stdlib.h>
// Function to allocate memory for a new PolyNode and initialize its fields
PolyPointer getnode(void) {
PolyPointer temp;
temp = (PolyPointer)malloc(sizeof(PolyNode));
if (temp == NULL) {
fprintf(stderr, "Memory allocation failed.\n");
exit(EXIT_FAILURE);
}
return temp;
}
do {
int coef, expon;
printf("Enter coefficient: ");
scanf("%d", &coef);
printf("Enter exponent: ");
scanf("%d", &expon);
return poly;
}
int main() {
printf("Enter polynomial coefficients and exponents:\n");
PolyPointer poly = createPolynomial();
int x;
printf("Enter the value of x: ");
scanf("%d", &x);
return 0;
}
Output:
#include <stdio.h>
#include <stdlib.h>
// Function to allocate memory for a new PolyNode and initialize its fields
PolyPointer getnode(void) {
PolyPointer temp;
temp = (PolyPointer)malloc(sizeof(PolyNode));
if (temp == NULL) {
fprintf(stderr, "Memory allocation failed.\n");
exit(EXIT_FAILURE);
}
return temp;
}
int sum;
rear = getnode();
c = rear;
while (a && b) {
switch (compare(a->expon, b->expon)) {
case -1:
/* a->expon < b->expon */
attach(b->coef, b->expon, &rear);
b = b->next;
break;
case 0:
/* a->expon = b->expon */
sum = a->coef + b->coef;
if (sum) {
attach(sum, a->expon, &rear);
a = a->next;
b = b->next;
}
break;
case 1:
/* a->expon > b->expon */
attach(a->coef, a->expon, &rear);
a = a->next;
break;
}
}
/* copy rest of list a and then list b */
for (; a; a = a->next)
attach(a->coef, a->expon, &rear);
for (; b; b = b->next)
attach(b->coef, b->expon, &rear);
rear->next = NULL;
return c;
}
do {
int coef, expon;
free (temp);
return poly;
}
int main() {
return 0;
}
Output:
Enter polynomial A:
Enter coefficient: 3
Enter exponent: 3
Add another term? (y/n): 1
Enter coefficient: 2
Enter exponent: 2
Add another term? (y/n): 1
Enter coefficient: 5
Enter exponent: 1
Add another term? (y/n): 1
Enter coefficient: 4
Enter exponent: 0
Add another term? (y/n): 0
Enter polynomial B:
Enter coefficient: 2
Enter exponent: 3
Add another term? (y/n): 1
Enter coefficient: 3
Enter exponent: 2
Add another term? (y/n): 1
Enter coefficient: 1
Enter exponent: 1
Add another term? (y/n): 1
Enter coefficient: 6
Enter exponent: 0
Add another term? (y/n): 0
#include <stdio.h>
//#include <conio.h>
#include <stdlib.h>
ListPointer tree;
return data;
}
if ( temp == NULL )
{
printf( "\n\n Allocation Failed\n\n" );
getchar(); //getch();
exit( EXIT_FAILURE );
}
else
{
temp->data = data;
temp->lLink = temp->rLink = NULL;
}
return temp;
}
while ( tree )
{
parent = tree;
if ( data.key == tree->data.key )
{
return NULL;
}
if ( data.key < tree->data.key )
{
tree = tree->lLink;
}
else
{
tree = tree->rLink;
}
}
return parent;
}
while ( 1 )
{
printf ( "\n\nChoice: " );
scanf ( "%d", &choice );
switch ( choice )
{
case 1: printf("\n.. * INSERTION ..\n");
printf( "\nHow many RECORDS: " );
scanf( "%d", &nRecords );
1. Insert
5. Exit
Choice: 1
.. * INSERTION ..
Choice: 2
Inorder Traversal
2 5 6 7 8 9 14 15 24
Choice: 3
Preorder Traversal
6 5 2 9 8 7 15 14 24
Choice: 4
Postorder Traversal
2 5 7 8 14 24 15 9 6
Choice: 5
EXIT
11.OPERATIONS ON GRAPH.
Design, Develop and implement 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 the DFS/BFS method.
#include <stdio.h>
#include <stdlib.h>
#define N 8
int adj[][N + 1] = {
{ 0, 1, 2, 3, 4, 5, 6, 7, 8},
{ 1, 0, 1, 1, 0, 0, 0, 0, 0},
{ 2, 1, 0, 0, 1, 1, 0, 0, 0},
{ 3, 1, 0, 0, 0, 0, 1, 1, 0},
{ 4, 0, 1, 0, 0, 0, 0, 0, 1},
{ 5, 0, 1, 0, 0, 0, 0, 0, 1},
{ 6, 0, 0, 1, 0, 0, 0, 0, 1},
{ 7, 0, 0, 1, 0, 0, 0, 0, 1},
{ 8, 0, 0, 0, 1, 1, 1, 1, 0}
};
#define N 7
int adj[][N + 1] = {
{ 0, 1, 2, 3, 4, 5, 6, 7},
{ 1, 0, 1, 0, 0, 0, 1, 0},
{ 2, 1, 0, 1, 0, 0, 0, 1},
{ 3, 0, 1, 0, 1, 0, 0, 0},
{ 4, 0, 0, 1, 0, 1, 0, 1},
{ 5, 0, 0, 0, 1, 0, 1, 1},
{ 6, 1, 0, 0, 0, 1, 0, 0},
{ 7, 0, 1, 0, 1, 1, 0, 0}
};
do{
printf ("\n\n\t\t\t\tGRAPH DEMONSTRATION\n\n" );
printf ("\n\n\t\t1. Display Matrix\n\n" );
printf ("\n\n\t\t2. DFS\t\t3. Exit\n\n" );
switch ( ch )
{
case 1: displayMatrix ( );
break;
case 2: printf ( "\n\nEnter the Source Vertex: ?\b" );
scanf ( "%d", &sVertex );
dfs ( sVertex );
break;
case 3: return 0;
default: printf ( "\n\nInvalid Option\n\n" );
}
fflush(stdin);
getchar();
}while ( 1 );
}
OUTPUT:-
GRAPH DEMONSTRATION
1. Display Matrix
2. DFS 3. Exit
Adjacency matrix
0 1 1 0 0 0 0 0
1 0 0 1 1 0 0 0
1 0 0 0 0 1 1 0
0 1 0 0 0 0 0 1
0 1 0 0 0 0 0 1
0 0 1 0 0 0 0 1
0 0 1 0 0 0 0 1
0 0 0 1 1 1 1 0
GRAPH DEMONSTRATION
1. Display Matrix
2. DFS 3. Exit
GRAPH DEMONSTRATION
1. Display Matrix
2. DFS 3. Exit
RUN 2:
GRAPH DEMONSTRATION
1. Display Matrix
2. DFS 3. Exit
Adjacency matrix
0 1 0 0 0 1 0
1 0 1 0 0 0 1
0 1 0 1 0 0 0
0 0 1 0 1 0 1
0 0 0 1 0 1 1
1 0 0 0 1 0 0
0 1 0 1 1 0 0
GRAPH DEMONSTRATION
1. Display Matrix
2. DFS 3. Exit
1. Display Matrix
2. DFS 3. Exit
#include <stdio.h>
//#include <conio.h>
#include <stdlib.h>
#include <string.h>
#define NO_OF_BUCKETS 13
typedef enum
{
available, duplicate, bucket_full
}Status;
ListPointer ht[NO_OF_BUCKETS];
return data;
}
if ( temp == NULL )
{
printf ( "\n\n Allocation Failed\n\n" );
getchar (); //getch();
exit ( EXIT_FAILURE );
}
else
{
temp->data = data;
}
return temp;
}
while ( *key )
number += *key ++;
return number;
}
k = stringToInt ( key );
return k % NO_OF_BUCKETS;
}
currentBucket = homeBucket;
while ( ht[currentBucket]
&&
strcmp ( ht[currentBucket]->data.SSN, key ) != 0 )
{
currentBucket = ( currentBucket + 1 ) % NO_OF_BUCKETS;
/* treat the table as circular */
if ( currentBucket == homeBucket )
return bucket_full; /* back to start point */
}
if ( ht[currentBucket] )
{
if ( strcmp ( ht[currentBucket]->data.SSN, key ) == 0 )
return duplicate;
}
return available;
}
switch ( state )
{
case available: if ( ht[homeBucket] != NULL )
{
printf ( "\n\n Collision is Detected at
the Index:
%d", homeBucket );
printf ( "\n\n Issue is solved by Linear
probing
with the new Index: %d\n\n", currentBucket );
}
ht[currentBucket] = getNode ( data );
break;
case duplicate: printf("\nDuplicate key: %s\n", data.SSN);
break;
case bucket_full: printf("\nAll buckets are occupied\n");
}
}
printf("\nEmployee details...\n");
printf("\nINDEX\tSSN\tNAME\tDEPT.\tSALARY\n");
for ( i = 0; i < NO_OF_BUCKETS; ++ i )
{
if ( ht[i])
{
printf ( "\n[%d] - %s\t", i, ht[i]->data.SSN );
printf ( "%s\t", ht[i]->data.name );
printf ( "%s\t", ht[i]->data.dept );
printf ( "%s\n", ht[i]->data.salary );
}
else
{
printf ( "\n[%d] - %s\n", i, " " );
}
}
}
while ( 1 )
{
printf ( "\nEnter your Choice: " );
scanf ( "%d", &choice );
switch ( choice )
{
case 1: printf ( "\nHow many records: " );
scanf ( "%d", &nRecords );
[5] -
1. Insertion
[6] -
2. Display
[7] -
3. Exit
[8] - two Kate CSE 2222
Enter your Choice: 1
[9] -
How many records: 6
[10] - one MartinCSE 1111
Give 6 record details one by one
[11] - five DanielECE 3333
SSN NAMEDEPT. SALARY
One Martin CSE 1111 [12] -
Two Kate CSE 2222
Three Brian ISE 5555 Enter your Choice: 3
Four Kathy ECE 4444 Exit
Five Daniel ECE 3333
3. Exit
Collision is Detected at the Index:
Enter your Choice: 1 2
This C program implements a hash table using the remainder method to map a
given key K to the address space L. It uses linear probing to resolve any
collisions.
The program defines a struct called EmployeeRecord, which contains the fields
SSN, name, dept, and salary. It also defines a struct called Node, which
contains an EmployeeRecord and a link to the next Node. The program creates an
array of linked lists called ht, where each element of the array is a pointer
to a Node. The number of elements in the array is defined by the macro
NO_OF_BUCKETS, which is set to 13.
The program defines an enum called Status, which has three possible values:
available, duplicate, and bucket_full. The program uses this enum to keep
track of the status of a bucket when inserting an EmployeeRecord into the hash
table.
The program defines several functions. The getNextRecord function reads input
from the user and returns an EmployeeRecord struct. The getNode function takes
an EmployeeRecord as input and returns a pointer to a new Node containing that
EmployeeRecord. The stringToInt function takes a string as input and returns
the sum of the ASCII values of its characters. The myHash function takes a
string as input, converts it to an integer using stringToInt, and returns the
integer modulo NO_OF_BUCKETS.
The main function of the program reads input from the user and inserts it into
the hash table. It uses the myHash function to determine the homeBucket of the
input, and if that bucket is available, it inserts the input into the linked
list at that bucket. If the homeBucket is not available, it uses linear
probing to search for an available bucket, starting from the homeBucket and
wrapping around to the beginning of the array if necessary. If it finds an
available bucket, it inserts the input into the linked list at that bucket. If
it encounters a duplicate input, it sets the status to duplicate and stops
searching. If it reaches the homeBucket again without finding an available
bucket, it sets the status to bucket_full and stops searching.