Laboratory Component: Data Structures Laboratory (BCSL305) : Department of Computer Science and Engineering

Download as pdf or txt
Download as pdf or txt
You are on page 1of 101

Bapuji Educational Association (Regd.

)
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)

Department of Computer Science and Engineering

Ⅲ Semester

Laboratory Component:
DATA STRUCTURES LABORATORY
[BCSL305]

Prepared by:
Dr. Naveen KUmar K R
Associate Professor
Dept. of CSE
BIET
Vision

To be a centre-of-excellence by imbibing state-of-the-art technology in the field of Computer


Science and Engineering, thereby enabling students to excel professionally and be ethical.

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.

Program Educational Objectives (PEOs)

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.

Program Specific Outcomes (PSOs)

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

1.ARRAY CREATION USING DYNAMIC MEMORY ALLOCATION......................................... 6

2.PATTERN MATCHING OPERATION.......................................................................................... 11

3. IMPLEMENTATION OF STACK................................................................................................. 15

4. INFIX EXPRESSION TO POSTFIX EXPRESSION..............................................................25

5. STACK APPLICATIONS............................................................................................................... 28

a. Evaluation of Suffix expression with single digit operands and operators: +, -,

*, /, %, ^......................................................................................................................................... 28

b. Solving Tower of Hanoi problem with n disks............................................................. 32

6. OPERATIONS ON CIRCULAR QUEUE....................................................................................34

7. OPERATIONS ON SINGLY LINKED LIST (SLL)................................................................. 40

8. OPERATIONS ON DOUBLY LINKED LIST (DLL)................................................................55

9. POLYNOMIAL OPERATIONS.....................................................................................................65

a. Represent and Evaluate a Polynomial........................................................................... 65

b. Find the sum of two polynomials and store the result.............................................69

10. OPERATIONS ON BINARY SEARCH TREE (BST)............................................................. 74

11.OPERATIONS ON GRAPH..........................................................................................................81

12.HASHING........................................................................................................................................87
Laboratory Outcomes:

The student should be able to:

1. Analyze various linear and non-linear data structures

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:

1. pwd: Print working directory

2. ls: List directory contents

- `-l`: Long format

- `-a`: Include hidden files

3. cd: Change directory

- `cd <directory>`: Change to the specified directory

- `cd ..`: Move up one level

4. mkdir: Make directory

- `mkdir <directory_name>`: Create a new directory

5. rm: Remove files or directories

- `-r`: Recursive (used for removing directories)

- `-f`: Force (ignore non-existent files and do not prompt)

6. cp: Copy files or directories

- `-r`: Recursive (used for copying directories)

- `-i`: Interactive (prompt before overwriting)

7. mv: Move (rename) files or directories

8. touch: Create an empty file or update the access and modification times of a file

- `touch <filename>`

9. cat: Concatenate and display the content of files

10. echo: Display a message or turn command echoing on/off

11. man: Display the manual for a command

- `man <command>`: Display manual for the specified command

12. chmod: Change file permissions

- `chmod <permissions> <filename>`: Change the permissions of a file


13. chown: Change file owner and group

- `chown <owner:group> <filename>`: Change the owner and group of a file

14. ps: Display information about active processes

- `ps aux`: Display detailed information about all processes

15. kill: Terminate a process

- `kill <process_id>`: Terminate a process by its ID

16. grep: Search for a pattern in files

- `grep <pattern> <filename>`: Search for a pattern in a file

17. find: Search for files and directories

- `find <directory> -name <filename>`: Search for a file in a directory

18. tar: Archive and compress files

- `tar -cvf <archive_name>.tar <files>`: Create a tar archive

- `tar -xvf <archive_name>.tar`: Extract files from a tar archive


CYGWIN
Cygwin is a Unix-like environment and command-line interface for Microsoft Windows.
It provides users with a way to run native Linux applications on Windows. Cygwin
consists of a DLL (cygwin1.dll), which acts as a Linux emulation layer providing
substantial Linux API functionality. It also includes a collection of tools and utilities
that provide a Unix-like environment on Windows, including shells, compilers, text
editors, and other development tools. Cygwin is often used by developers who want to
develop and test software on Windows while still having access to Unix-like tools and
environments.

Cygwin can be a valuable tool for several reasons:

1. Unix-like Environment on Windows: Many CSE students may be required to


work with Unix-based systems during their coursework or in their careers.
Cygwin allows them to have a Unix-like environment directly on their Windows
machines, enabling them to use familiar tools and commands.

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.

3. Learning Experience: Using Cygwin can provide students with exposure to


Unix-like operating systems and command-line interfaces, which are commonly
used in software development and system administration roles. This experience
can be valuable for understanding concepts such as file systems, processes,
and shell scripting.

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.

5. Open Source Development: Many open-source projects are designed to be


built and run on Unix-like systems. By using Cygwin, CSE students can
contribute to open-source projects and gain experience with collaborative
software development.

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:

- Normal Mode: For navigation and manipulation of text.

- Insert Mode: For inserting new text.

- Visual Mode: For selecting blocks of text.

- Command-Line Mode: For entering commands like saving files or searching.

2. Customization: Vim is highly customizable. Users can define custom key


mappings, configure behavior through its settings, and even extend its
functionality through plugins and scripting in Vimscript or other supported
languages like Python or Lua.

3. Efficiency: Vim is designed for efficiency. Its modal editing, extensive


keyboard shortcuts, and powerful editing commands allow users to perform
complex text manipulation tasks quickly once they become familiar with its
usage.

4. Syntax Highlighting: Vim supports syntax highlighting for a wide range of


programming languages and file types, making it easier to read and edit code.

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.

7. Portability: Vim is available on many platforms, including Unix-like systems


(Linux, macOS, BSD), Windows, and others, making it a versatile choice for
developers working across different environments.
1.ARRAY CREATION USING DYNAMIC MEMORY
ALLOCATION.

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 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 structure for a Day


typedef struct {
char *name;
int date;
char *activity;
} Day;

// Function to create a calendar


Day* create() {
Day* week = malloc(7 * sizeof(Day));
return week;
}

// Function to read data from the console


void read(Day* week) {
char buffer[256];
for (int i = 0; i < 7; i++) {
printf("Enter name of day %d: ", i+1);
scanf("%s", buffer);
week[i].name = malloc(strlen(buffer) + 1);
strcpy(week[i].name, buffer);

printf("Enter date of day %d: ", i+1);


scanf("%d", &week[i].date);

printf("Enter activity of day %d: ", i+1);


scanf(" %[^\n]", buffer);
week[i].activity = malloc(strlen(buffer) + 1);
strcpy(week[i].activity, buffer);
}
}

// Function to display the week's activities


void display(Day* week) {
for (int i = 0; i < 7; i++) {
printf("Day: %s\n", week[i].name);
printf("Date: %d\n", week[i].date);
printf("Activity: %s\n", week[i].activity);
}
}

// Main function
int main() {
Day* week = create();
read(week);
display(week);
free(week);
return 0;
}
OUTPUT:

**Input:** **Output:**

Day name: Sunday Day: Sunday


Date: 1 Date: 1
Activity: Go to church Activity: Go to church

Day name: Monday Day: Monday


Date: 2 Date: 2
Activity: Work Activity: Work

Day name: Tuesday Day: Tuesday


Date: 3 Date: 3
Activity: Work Activity: Work

Day name: Wednesday Day: Wednesday


Date: 4 Date: 4
Activity: Work Activity: Work

Day name: Thursday Day: Thursday


Date: 5 Date: 5
Activity: Work Activity: Work

Day name: Friday Day: Friday


Date: 6 Date: 6
Activity: Work Activity: Work

Day name: Saturday Day: Saturday


Date: 7 Date: 7
Activity: Time to relax Activity: Time to relax
Program explanation:

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.

3. `Day* create()` is a function that dynamically creates an array of 7 `Day` structures. It


returns the pointer to the first element of this array.

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.

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>

int myStrLen(char *str) {


int len = 0;
while (*str++ != '\0') {
len++;
}
return len;
}

void myStrCpy(char *s1, char *s2) {


while ((*s1++ = *s2++) != '\0');
}

void myStrCat(char *s1, char *s2) {


while (*s1 != '\0') {
s1++;
}
myStrCpy(s1, s2);
}

int strReplace(char *str, char *pat, char *rep) {


int i = 0, j = 0, k;
int flag = 0;
int strLen = myStrLen(str);
int patLen = myStrLen(pat);
int repLen = myStrLen(rep);

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


k = i;
for (j = 0; j < patLen; j++) {
if (str[k++] != pat[j]) {
break;
}
}
if (j == patLen) {
flag = 1;
char *temp = (char *)malloc(strLen + repLen - patLen + 1);
myStrCpy(temp, str);
myStrCpy(temp + i, rep);
myStrCat(temp + i + repLen, str + i + patLen);
myStrCpy(str, temp);
free(temp);
return flag;
}
}
return flag;
}

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);

STR[myStrLen(STR) - 1] = '\0'; // Remove newline at end if any


PAT[myStrLen(PAT) - 1] = '\0'; // Remove newline at end if any
REP[myStrLen(REP) - 1] = '\0'; // Remove newline at end if any

if (!strReplace(STR, PAT, REP)) {


printf("Pattern string (PAT) not found in main string (STR).\n");
} else {
printf("Modified main string (STR) is: %s\n", STR);
}

return 0;
}
OUTPUT:

**Input:**

Enter main string (STR): I enjoy programming with C.


Enter pattern string (PAT): programming
Enter replace string (REP): coding

**Output:**

Modified main string (STR) is: I enjoy coding with C.

---

Example where the pattern does not exist in the main string:

**Input:**

Enter main string (STR): I enjoy programming with C.


Enter pattern string (PAT): cooking
Enter replace string (REP): coding

**Output:**

Pattern string (PAT) not found in main string (STR).


Program explanation:

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()`.

2. Three custom string-related functions are declared:

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.

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>

#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);
}

void push(int value) {


if (isFull()) {
printf("Stack Overflow!\n");
} else {
stack[++top] = value;
printf("%d pushed to stack.\n", value);
}
}

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.

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: 20
20 pushed to stack.

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: 20
20 pushed to stack.

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.

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): 5
Stack elements are:
10
20
20
10

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): 4
Stack is neither full nor empty.

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): 3
Stack contents are a palindrome.

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): 2
Popped element: 10

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): 2
Popped element: 20

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): 2
Popped element: 20

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): 2
Popped element: 10

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): 4
Stack Underflow!

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.

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: 20
20 pushed to stack.

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: 30
30 pushed to stack.

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: 40
40 pushed to stack.

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: 50
50 pushed to stack.

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: 60
60 pushed to stack.

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: 70
70 pushed to stack.

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: 80
80 pushed to stack.

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: 90
90 pushed to stack.

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: 100
100 pushed to stack.

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): 4
Stack Overflow!

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): 3
Stack contents are not a palindrome.

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): 6
4. INFIX EXPRESSION TO POSTFIX EXPRESSION.

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 <string.h>
#include <ctype.h>

#define MAX 100

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

void push(char item) {


if (top == MAX - 1) {
printf("Stack Overflow\n");
} else {
top++;
stack[top] = item;
}
}

char pop() {
if (top == -1) {
printf("Stack Underflow\n");
return -1;
} else {
return stack[top--];
}
}

int precedence(char symbol) {


if (symbol == '^') {
return 3;
} else if (symbol == '*' || symbol == '/' || symbol == '%') {
return 2;
} else if (symbol == '+' || symbol == '-') {
return 1;
} else {
return 0;
}
}

int isOperator(char symbol) {


if (symbol == '^' || symbol == '*' || symbol == '/' || symbol == '%' ||
symbol == '+' || symbol == '-') {
return 1;
} else {
return 0;
}
}

void infixToPostfix(char infix[], char postfix[]) {


int i, j = 0;
char symbol;
for (i = 0; infix[i] != '\0'; i++) {
symbol = infix[i];
if (isalnum(symbol)) {
postfix[j++] = symbol;
} else if (symbol == '(') {
push(symbol);
} else if (symbol == ')') {
while (stack[top] != '(') {
postfix[j++] = pop();
}
pop();
} else if (isOperator(symbol)) {
while (precedence(stack[top]) >= precedence(symbol)) {
postfix[j++] = pop();
}
push(symbol);
}
}
while (top != -1) {
postfix[j++] = pop();
}
postfix[j] = '\0';
}

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:

Input Infix Expression: (A+B)*C-D/E^F

Output Postfix Expression: AB+C*DEF^/-


5. STACK APPLICATIONS

a. Evaluation of Suffix expression with single digit operands and operators:


+, -, *, /, %, ^.

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

#define MAX 10

int top = -1;


int stack[MAX];

void push(int value) {


if(top >= (MAX-1)) {
printf("Stack Overflow\n");
}
else {
stack[++top] = value;
}
}

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;
}
}

int evaluate_postfix(char *postfix) {


int i, op1, op2;
char c;

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


c = postfix[i];

if(c >= '0' && c <= '9') {


push(c - '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;

printf("Enter a postfix expression: ");


scanf("%s", postfix);

result = evaluate_postfix(postfix);

if(result != -1)
printf("Result: %d\n", result);

return 0;
}

OUTPUT:

Enter a postfix expression: 62/3-42^+5+


Result: 21
Explanation:

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>

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: 3

Move disk 1 from rod A to rod C


Move disk 2 from rod A to rod B
Move disk 1 from rod C to rod B
Move disk 3 from rod A to rod C
Move disk 1 from rod B to rod A
Move disk 2 from rod B to rod C
Move disk 1 from rod A to rod C
Explanation:

1. Recursive Function towerOfHanoi:


○ It takes four parameters: number of disks (n), source rod (from_rod), destination
rod (to_rod), and auxiliary rod (aux_rod).
○ Base Case: If n is 1, move the disk directly from source to destination.
○ Recursive Case:
■ Move the top n-1 disks from source to auxiliary rod using the destination
rod as a temporary rod.
■ Move the largest disk (disk n) from source to destination rod.
■ Move the n-1 disks from auxiliary to destination rod using the source rod
as a temporary rod.
2. main Function:
○ Prompts the user to enter the number of disks.
○ Calls the towerOfHanoi function with initial parameters (n disks, starting rod A,
destination rod C, and auxiliary rod B).
6. OPERATIONS ON CIRCULAR QUEUE
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

Updated on: Feb 13, 2024

#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;
}

// Function to handle queue-full situation


void queueFull() {
printf("Queue is full. Overflow occurred.\n");

if(front == 0){
rear = MAX_QUEUE_SIZE - 1;
} else{
rear = front - 1;
}
}

// Function to handle queue-empty situation


char queueEmpty() {
printf("Queue is empty. Underflow occurred.\n");

return '\0'; // Returning null character as the error key


}

// Function to add an item to the queue


void addq(char item) {
rear = (rear + 1) % MAX_QUEUE_SIZE;

if (front == rear) {
queueFull();
return;
}

queue[rear] = item;
}

// Function to remove front element from the queue


char deleteq() {
if (front == rear) {
return queueEmpty();
}
front = (front + 1) % MAX_QUEUE_SIZE;
return queue[front];
}

// Function to display the status of the queue


void displayStatus() {
printf("Current Queue status: ");
if (front == rear) {
printf("Empty\n");
} else {
int i;
for (i = (front + 1) % MAX_QUEUE_SIZE; i != rear; i = (i + 1) %
MAX_QUEUE_SIZE) {
printf("%c ", queue[i]);
}
printf("%c\n", queue[i]);
}
}

void processChoice(int choice) {


char 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:

Menu: Enter your choice: 1


1. Insert an Element Enter the element to insert: A
2. Delete an Element
3. Demonstrate Overflow Menu:
4. Demonstrate Underflow 1. Insert an Element
5. Display the status 2. Delete an Element
6. Exit 3. Demonstrate Overflow
4. Demonstrate Underflow Displaying the status of Circular QUEUE:
5. Display the status Current Queue status: A B C D
6. Exit
Enter your choice: 1 Menu:
Enter the element to insert: B 1. Insert an Element
2. Delete an Element
Menu: 3. Demonstrate Overflow
1. Insert an Element 4. Demonstrate Underflow
2. Delete an Element 5. Display the status
3. Demonstrate Overflow 6. Exit
4. Demonstrate Underflow Enter your choice: 2
5. Display the status Deleted element: A
6. Exit
Enter your choice: 1 Menu:
Enter the element to insert: C 1. Insert an Element
2. Delete an Element
Menu: 3. Demonstrate Overflow
1. Insert an Element 4. Demonstrate Underflow
2. Delete an Element 5. Display the status
3. Demonstrate Overflow 6. Exit
4. Demonstrate Underflow Enter your choice: 2
5. Display the status Deleted element: B
6. Exit
Enter your choice: 1 Menu:
Enter the element to insert: D 1. Insert an Element
2. Delete an Element
Menu: 3. Demonstrate Overflow
1. Insert an Element 4. Demonstrate Underflow
2. Delete an Element 5. Display the status
3. Demonstrate Overflow 6. Exit
4. Demonstrate Underflow Enter your choice: 2
5. Display the status Deleted element: C
6. Exit
Enter your choice: 1 Menu:
Enter the element to insert: E 1. Insert an Element
Queue is full. Overflow occurred. 2. Delete an Element
3. Demonstrate Overflow
Menu: 4. Demonstrate Underflow
1. Insert an Element 5. Display the status
2. Delete an Element 6. Exit
3. Demonstrate Overflow Enter your choice: 2
4. Demonstrate Underflow Deleted element: D
5. Display the status
6. Exit Menu:
Enter your choice: 5 1. Insert an Element
2. Delete an Element Menu:
3. Demonstrate Overflow 1. Insert an Element
4. Demonstrate Underflow 2. Delete an Element
5. Display the status 3. Demonstrate Overflow
6. Exit 4. Demonstrate Underflow
Enter your choice: 2 5. Display the status
Queue is empty. Underflow occurred. 6. Exit
Enter your choice: 4
Menu: Demonstrating Underflow...
1. Insert an Element Queue is empty. Underflow occurred.
2. Delete an Element Current Queue status: Empty
3. Demonstrate Overflow
4. Demonstrate Underflow Menu:
5. Display the status 1. Insert an Element
6. Exit 2. Delete an Element
Enter your choice: 3 3. Demonstrate Overflow
Demonstrating Overflow... 4. Demonstrate Underflow
Queue is full. Overflow occurred. 5. Display the status
Queue is full. Overflow occurred. 6. Exit
Current Queue status: A B C D Enter your choice: 6
Exiting...
7. OPERATIONS ON SINGLY LINKED LIST (SLL)
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
Updated on: Feb 27, 2024

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

// Define the StudentInfo structure


typedef struct {
char usn[15];
char name[50];
char programme[50];
int sem;
char phno[15];
} StudentInfo;

// Define the Student node structure


typedef struct StudentNode{
StudentInfo data;
struct StudentNode *next;
} StudentNode;

// Define the StudentPointer alias


typedef struct StudentNode *StudentPointer;

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;
}

// Function to read data for a student


StudentInfo readStudentData() {
StudentInfo newStudent;

printf("Enter USN: ");


scanf("%14s", newStudent.usn);

printf("Enter Name: ");


scanf(" %[^\n]", newStudent.name);

printf("Enter Programme: ");


scanf(" %[^\n]", newStudent.programme);

printf("Enter Semester: ");


scanf("%d", &newStudent.sem);

printf("Enter Phone Number: ");


scanf("%14s", newStudent.phno);

return newStudent;
}

// Function to create a new node


StudentPointer getNode(StudentInfo data) {
// Allocate memory for the new node
StudentPointer newNode = (StudentPointer)malloc(sizeof(StudentNode));

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;
}

// Function to insert a node at the front


void insertFront(StudentPointer newNode) {
newNode->next = first;
first = newNode;
}

// Function to insert a node at the end


void insertEnd(StudentPointer newNode) {

if (first == NULL) {
first = newNode;
return;
}

StudentPointer last = first;


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

last->next = newNode;
}

// Function to delete a node from the front


void deleteFront() {
if (first == NULL) {
printf("List is empty, can not delete.\n");
return;
}

StudentPointer tempNode = first;


first = first->next;
free(tempNode);
}

// Function to delete a node from the end


void deleteEnd() {
if (first == NULL) {
printf("List is empty, can not delete.\n");
return;
}

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

StudentPointer second_last = first;


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

free(second_last->next);
second_last->next = NULL;
}

// Function to count the number of nodes


int countNodes(void) {
int count = 0;
StudentPointer current = first;
while (current != NULL) {
count++;
current = current->next;
}
return count;
}

// Function to display the list


void display() {
StudentPointer ptr = first;
while (ptr) {
printf("USN: %s, Name: %s, Programme: %s, Semester: %d, Phone No:
%s\n", ptr->data.usn, ptr->data.name, ptr->data.programme, ptr->data.sem,
ptr->data.phno);
ptr = ptr->next;
}
printf("Total nodes: %d\n", countNodes());
}

void processChoice(int choice) {


int n, i;
StudentInfo newStudent;
StudentPointer newStudentNode;

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:

****** Menu ******

1. Insert at Front

2. Insert at End

3. Delete from Front

4. Delete from End

5. Display

6. Exit

Enter your choice: 1

Enter USN, Name, Programme, Semester, Phone No:

111 John CSE 3 11111

****** Menu ******

1. Insert at Front

2. Insert at End

3. Delete from Front

4. Delete from End

5. Display

6. Exit

Enter your choice: 1

Enter USN, Name, Programme, Semester, Phone No:

222 Jack CSE 5 22222

****** Menu ******

1. Insert at Front

2. Insert at End
3. Delete from Front

4. Delete from End

5. Display

6. Exit

Enter your choice: 1

Enter USN, Name, Programme, Semester, Phone No:

333 Kate ISE 7 33333

****** Menu ******

1. Insert at Front

2. Insert at End

3. Delete from Front

4. Delete from End

5. Display

6. Exit

Enter your choice: 5

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

****** Menu ******

1. Insert at Front

2. Insert at End

3. Delete from Front

4. Delete from End

5. Display
6. Exit

Enter your choice: 2

Enter USN, Name, Programme, Semester, Phone No:

444 Kathy ECE 2 44444

****** Menu ******

1. Insert at Front

2. Insert at End

3. Delete from Front

4. Delete from End

5. Display

6. Exit

Enter your choice: 2

Enter USN, Name, Programme, Semester, Phone No:

555 Robert ECE 4 55555

****** Menu ******

1. Insert at Front

2. Insert at End

3. Delete from Front

4. Delete from End

5. Display

6. Exit

Enter your choice: 2

Enter USN, Name, Programme, Semester, Phone No:

666 David EEE 6 66666


****** Menu ******

1. Insert at Front

2. Insert at End

3. Delete from Front

4. Delete from End

5. Display

6. Exit

Enter your choice: 5

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

****** Menu ******

1. Insert at Front

2. Insert at End

3. Delete from Front

4. Delete from End

5. Display

6. Exit

Enter your choice: 3

****** Menu ******

1. Insert at Front
2. Insert at End

3. Delete from Front

4. Delete from End

5. Display

6. Exit

Enter your choice: 2

Enter USN, Name, Programme, Semester, Phone No:

666 David EEE 6 66666

****** Menu ******

1. Insert at Front

2. Insert at End

3. Delete from Front

4. Delete from End

5. Display

6. Exit

Enter your choice: 5

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

****** Menu ******

1. Insert at Front
2. Insert at End

3. Delete from Front

4. Delete from End

5. Display

6. Exit

Enter your choice: 3

****** Menu ******

1. Insert at Front

2. Insert at End

3. Delete from Front

4. Delete from End

5. Display

6. Exit

Enter your choice: 5

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

****** Menu ******

1. Insert at Front

2. Insert at End

3. Delete from Front

4. Delete from End


5. Display

6. Exit

Enter your choice: 4

****** Menu ******

1. Insert at Front

2. Insert at End

3. Delete from Front

4. Delete from End

5. Display

6. Exit

Enter your choice: 5

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

****** Menu ******

1. Insert at Front

2. Insert at End

3. Delete from Front

4. Delete from End

5. Display

6. Exit

Enter your choice: 6


Explanation:

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)

* programme (program name)

* sem (semester)

* phno (phone number)

* next (pointer to the next node in the list)

2. The next section of the code defines five functions:

* 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

* 3: Delete from front

* 4: Delete from 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;

// Define the Employee node structure


typedef struct EmployeeNode {
struct EmployeeNode *llink;
EmployeeInfo data;
struct EmployeeNode *rlink;
} EmployeeNode;

// Define the EmployeePointer alias


typedef struct EmployeeNode *EmployeePointer;

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;
}

// Function to read data for an employee


EmployeeInfo readEmployeeData() {
EmployeeInfo newEmployee;

printf("Enter Social Security Number: ");


scanf("%14s", newEmployee.socialSecurityNumber);

printf("Enter Full Name: ");


scanf(" %[^\n]", newEmployee.fullName);

printf("Enter Department: ");


scanf(" %[^\n]", newEmployee.department);

printf("Enter Job Designation: ");


scanf(" %[^\n]", newEmployee.jobDesignation);

printf("Enter Salary: ");


scanf("%f", &newEmployee.salary);

printf("Enter Phone Number: ");


scanf("%14s", newEmployee.phoneNumber);

return newEmployee;
}

// Function to create a new circular node


EmployeePointer getNode(EmployeeInfo data) {
// Allocate memory for the new node
EmployeePointer newNode = (EmployeePointer)malloc(sizeof(EmployeeNode));

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 dinsert(EmployeePointer node, EmployeePointer newnode) {


/* insert newnode to the right of node */
newnode->llink = node;
newnode->rlink = node->rlink;
node->rlink->llink = newnode;
node->rlink = newnode;
}

void ddelete(EmployeePointer node, EmployeePointer deleted) {


/* delete from the doubly linked list */
if (node == deleted)
printf("Deletion of header node not permitted.\n");
else {
deleted->llink->rlink = deleted->rlink;
deleted->rlink->llink = deleted->llink;
free(deleted);
}
}

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
}
}

int countNodes(EmployeePointer head) {


int count = 0;
EmployeePointer current = head->rlink; // Start from the first node
while (current != head) {
count++;
current = current->rlink; // Move to the next node
}
return count;
}

void processChoice(int choice) {


int n, i;
EmployeePointer newEmployeeNode;
EmployeeInfo newEmployee;

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

Enter your choice: 1

Enter the number of employees: 3

Enter Social Security Number: 111


Enter Full Name: James
Enter Department: CSE
Enter Job Designation: Associate Professor
Enter Salary: 111111
Enter Phone Number: 987456123

Enter Social Security Number: 222


Enter Full Name: Anthony
Enter Department: ISE
Enter Job Designation: Professor
Enter Salary: 222222
Enter Phone Number: 978456123

Enter Social Security Number: 333


Enter Full Name: Jacob
Enter Department: CSE
Enter Job Designation: Assistant Professor
Enter Salary: 333333
Enter Phone Number: 974856123

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

Enter your choice: 2

Doubly Linked List:


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

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

Enter your choice: 3

Enter Social Security Number: 444


Enter Full Name: Daniel
Enter Department: ME
Enter Job Designation: Lecture
Enter Salary: 44444
Enter Phone Number: 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

Enter your choice: 2

Doubly Linked List:


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
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

Enter your choice: 5

Enter Social Security Number: 555


Enter Full Name: Ryan
Enter Department: EEE
Enter Job Designation: Professor
Enter Salary: 55555
Enter Phone Number: 967845123

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

Enter your choice: 2

Doubly Linked List:


SSN: 555, Name: Ryan , Dept: EEE , Designation: Professor, Sal: 55555.00, PhNo: 967845123

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

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
Enter your choice: 6

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

Enter your choice: 2

Doubly Linked List:


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

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

Enter your choice: 4

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

Enter your choice: 2

Doubly Linked List:


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

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

Enter your choice: 7

Exiting...
9. POLYNOMIAL OPERATIONS
Develop a Program in C for the following operations on Singly Circular
Linked List (SCLL) with header nodes

a. Represent and Evaluate a Polynomial.

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

// Definition of a structure representing a node in a polynomial


typedef struct PolyNode {
int coef;
int expon;
struct PolyNode *next; // Pointer to the next term in the polynomial
} PolyNode;

// Definition of a pointer type to the PolyNode structure


typedef struct PolyNode *PolyPointer;

// 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;
}

// Function to create a polynomial


PolyPointer createPolynomial() {
PolyPointer poly = NULL;
PolyPointer last = NULL;
int choice;

do {
int coef, expon;
printf("Enter coefficient: ");
scanf("%d", &coef);
printf("Enter exponent: ");
scanf("%d", &expon);

// Create a new node for the term


PolyPointer term = getnode();
term->coef = coef;
term->expon = expon;
term->next = NULL;

// Append the term to the polynomial


if (poly == NULL) {
poly = term;
last = term;
} else {
last->next = term;
last = term;
}

printf("Add another term? (1 for yes, 0 for no): ");


scanf("%d", &choice);
} while (choice == 1);

return poly;
}

int evaluatePoly(PolyPointer poly, int x) {


int result = 0;
while (poly != NULL) {
result = (result * x) + poly->coef;
poly = poly->next;
}
return result;
}

int main() {
printf("Enter polynomial coefficients and exponents:\n");
PolyPointer poly = createPolynomial();

int x;
printf("Enter the value of x: ");
scanf("%d", &x);

// Evaluate the polynomial


int result = evaluatePoly(poly, x);
printf("Result of polynomial evaluation at x = %d is: %d\n", x, result);

// Free the memory allocated for polynomial terms


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

return 0;
}
Output:

Enter polynomial coefficients and exponents:


Enter coefficient: 2
Enter exponent: 4
Add another term? (1 for yes, 0 for no): 1
Enter coefficient: -1
Enter exponent: 3
Add another term? (1 for yes, 0 for no): 1
Enter coefficient: 3
Enter exponent: 2
Add another term? (1 for yes, 0 for no): 1
Enter coefficient: 1
Enter exponent: 1
Add another term? (1 for yes, 0 for no): 1
Enter coefficient: -5
Enter exponent: 0
Add another term? (1 for yes, 0 for no): 0
Enter the value of x: 3
Result of polynomial evaluation at x = 3 is: 160
b. Find the sum of two polynomials and store the result.

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

// Definition of a structure representing a node in a polynomial


typedef struct PolyNode {
int coef;
int expon;
struct PolyNode *next; // Pointer to the next term in the polynomial
} PolyNode;

// Definition of a pointer type to the PolyNode structure


typedef struct PolyNode *PolyPointer;

// 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;
}

// Function to compare two exponents


int compare(int a, int b) {
if (a < b)
return -1;
else if (a == b)
return 0;
else
return 1;
}

// Function to attach a new term to the result polynomial


void attach(int coef, int expon, PolyPointer *rear) {
PolyPointer temp;
temp = getnode();
temp->coef = coef;
temp->expon = expon;
(*rear)->next = temp;
*rear = temp;
}

PolyPointer padd(PolyPointer a, PolyPointer b) {


/* return a polynomial which is the sum of a and b */

PolyPointer c, rear, 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;

/* delete extra initial node */


temp = c;
c = c->next;
free(temp);

return c;
}

void display(PolyPointer result) {


// Display the result polynomial
printf("\nResult of polynomial addition:\n");
while (result != NULL) {
printf("%dx^%d ", result->coef, result->expon);
result = result->next;
if (result != NULL)
printf("+ ");
}
printf("\n");
}

// Function to create a polynomial


PolyPointer createPolynomial() {
PolyPointer poly, last, temp;
int choice;

poly = last = getnode();

do {
int coef, expon;

printf("Enter coefficient: ");


scanf("%d", &coef);
printf("Enter exponent: ");
scanf("%d", &expon);

attach(coef, expon, &last);

printf("Add another term? (y/n): ");


scanf(" %d", &choice);

} while (choice == 1);


temp = poly;
poly = poly->next;

free (temp);

return poly;
}

int main() {

printf("Enter polynomial A:\n");


PolyPointer a = createPolynomial();

printf("Enter polynomial B:\n");


PolyPointer b = createPolynomial();

// Call padd function to add polynomials 'a' and 'b'


PolyPointer result = padd(a, b);

// Display the result


display(result);

// Clean up memory (free the result polynomial)


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

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

Result of polynomial addition:


5x^3 + 5x^2 + 6x^1 + 10x^0
10. OPERATIONS ON BINARY SEARCH TREE (BST)
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 Postorder
c. Search the BST for a given element (KEY) and report the
appropriate message
d. Exit
Updated on: Feb 26, 2024

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

typedef struct TreeData


{
int key;
}Record;

typedef struct Node *ListPointer;


typedef struct Node
{
ListPointer lLink;
Record data;
ListPointer rLink;
}Node;

ListPointer tree;

Record getNextRecord ( void )


{
Record data;

scanf ( "%d", &data.key );

return data;
}

ListPointer getNode ( Record data )


{
ListPointer temp;

temp = ( ListPointer ) malloc ( sizeof ( *temp ) );

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;
}

void inorder( ListPointer tree )


{
if ( tree )
{
inorder( tree->lLink );
printf( "%d\t", tree->data.key );
inorder( tree->rLink );
}
}

void preorder( ListPointer tree )


{
if( tree )
{
printf( "%d\t", tree->data.key );
preorder ( tree->lLink );
preorder ( tree->rLink );
}
}

void postorder ( ListPointer tree )


{
if ( tree )
{
postorder ( tree->lLink );
postorder ( tree->rLink );
printf( "%d\t", tree->data.key );
}
}

ListPointer modifiedSearch ( ListPointer tree, Record data )


{
ListPointer parent = NULL;

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;
}

void insert ( Record data )


{
ListPointer ptr, temp = modifiedSearch ( tree, data);
if ( temp || !tree )
{
ptr = getNode( data );
if ( tree )
{
if ( data.key < temp->data.key )
{
temp->lLink = ptr;
}
else
{
temp->rLink = ptr;
}
}
else
{
tree = ptr;
}
}
}

ListPointer search(ListPointer tree, Record data)


{
return true or NULL;
}

int main ( void )


{
Record data;
int nRecords;
int choice;
int i;

printf("\n.. BINARY SEARCH TREE DEMONSTRATION ..\n");


printf( "\n\n1. Insert\n");
printf( "\n2. Inoreder \t3. Preorder \t4. Postorder\n");
printf( "\n5. Search\n");
printf( "\n5. Exit\n");

while ( 1 )
{
printf ( "\n\nChoice: " );
scanf ( "%d", &choice );

switch ( choice )
{
case 1: printf("\n.. * INSERTION ..\n");
printf( "\nHow many RECORDS: " );
scanf( "%d", &nRecords );

printf("\nGive %d record details one by


one\n", nRecords);
for ( i = 0; i < nRecords; ++ i )
{
data = getNextRecord();
insert ( data );
}
break;
case 2: if ( tree )
{
printf( "\n\nInorder
Traversal\n\n" );
inorder ( tree );
}
else printf( "\n\nBST is Empty\n\n" );
break;
case 3: if ( tree )
{
printf( "\n\nPreorder
Traversal\n\n" );
preorder ( tree );
}
else
{
printf( "\n\nBST is Empty\n\n" );
}
break;
case 4: if ( tree )
{
printf( "\n\nPostorder
Traversal\n\n" );
postorder ( tree );
}
else
{
printf( "\n\nBST is Empty\n\n" );
}
break;
case 6: return 0;

default: printf( "\nWrong Choice\n" );


}
}
}
OUTPUT:
.. BINARY SEARCH TREE DEMONSTRATION ..

1. Insert

2. Inoreder 3. Preorder 4. Postorder

5. Exit

Choice: 1

.. * INSERTION ..

How many RECORDS: 12

Give 12 record details one by one


6
9
5
2
8
15
24
14
7
8
5
2

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.

1. Implementation using DFS 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}
};

int visited[N+1] = {0};


int count = 0;

void displayMatrix ( void )


{
int i, j;

printf ( "\n\nAdjacency matrix\n\n\n" );


for ( i = 1; i <= N; ++ i )
{
for ( j = 1; j <= N; ++ j )
printf ( "\t%d", adj[i][j] );
printf ( "\n\n" );
}
}

void dfs ( int v )


{
int w;
count = count + 1;
visited[v] = count;
printf ( "%-4d", v );
for ( w = 1; w <= N; ++ w )
{
if ( adj[v][w] && !visited[w] )
{
dfs ( w );
}
}
}

int main ( void )


{
int ch;
int i;
int sVertex;

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" );

printf ( "\n\nEnter your choice: ?\b" );


scanf ( "%d", &ch );

switch ( ch )
{
case 1: displayMatrix ( );
break;
case 2: printf ( "\n\nEnter the Source Vertex: ?\b" );
scanf ( "%d", &sVertex );

/* Resetting visited[] and count */


for ( i = 1; i <= N; ++ i ) visited[i] = 0;
count = 0;

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

Enter your choice: 1

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

Enter your choice: 2

Enter the Source Vertex: 1


1 2 4 8 5 6 3 7

GRAPH DEMONSTRATION

1. Display Matrix
2. DFS 3. Exit

Enter your choice: 3


Exit

RUN 2:
GRAPH DEMONSTRATION

1. Display Matrix

2. DFS 3. Exit

Enter your choice: 1

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

Enter your choice: 2

Enter the Source Vertex: 1


1 2 3 4 5 6 7
GRAPH DEMONSTRATION

1. Display Matrix

2. DFS 3. Exit

Enter your choice: 3


Exit
12.HASHING.
Design and develop a program in C that uses Hash Function H:K->L as
H(K)=K mod m(reminder 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 <conio.h>
#include <stdlib.h>
#include <string.h>

#define NO_OF_BUCKETS 13

typedef struct EmployeeRecord


{
char SSN[20];
char name[20];
char dept[20];
char salary[20];
}Record;

typedef struct Node *ListPointer;


typedef struct Node
{
Record data;
ListPointer link;
}Node;

typedef enum
{
available, duplicate, bucket_full
}Status;

ListPointer ht[NO_OF_BUCKETS];

int homeBucket, currentBucket;

Record getNextRecord ( void )


{
Record data;
scanf ( "%s", data.SSN );
scanf ( "%s", data.name );
scanf ( "%s", data.dept );
scanf ( "%s", data.salary );

return data;
}

ListPointer getNode ( Record data )


{
ListPointer temp;

temp = ( ListPointer ) malloc ( sizeof ( *temp ) );

if ( temp == NULL )
{
printf ( "\n\n Allocation Failed\n\n" );
getchar (); //getch();
exit ( EXIT_FAILURE );
}
else
{
temp->data = data;
}

return temp;
}

int stringToInt ( char *key )


{
int number = 0;

while ( *key )
number += *key ++;

return number;
}

int myHash ( char *key )


{
int k;

k = stringToInt ( key );
return k % NO_OF_BUCKETS;
}

Status search ( char *key )


{
homeBucket = myHash ( key );

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;
}

void insert ( Record data )


{
Status state;

state = search ( data.SSN);

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");
}
}

void display ( void )


{
int i;

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, " " );
}
}
}

int main ( void )


{
Record data;
int nRecords;
int choice;
int i;

printf("\n..HASH DEMONSTRATION WITH LINEAR PROBING..\n");


printf ( "\n\n1. Insertion\n\n2. Display\n\n3. Exit\n");

while ( 1 )
{
printf ( "\nEnter your Choice: " );
scanf ( "%d", &choice );

switch ( choice )
{
case 1: printf ( "\nHow many records: " );
scanf ( "%d", &nRecords );

printf("\nGive %d record details one by one\n",


nRecords);
printf("\nSSN\tNAME\tDEPT.\tSALARY\n");

for ( i = 0; i < nRecords; ++ i )


{
data = getNextRecord();
insert ( data );
}
break;
case 2: display ( );
break;
case 3: return 0;

default: printf ( "\nWrong Choice\n" );


}
}
}
Output:

..HASH DEMONSTRATION WITH LINEAR


PROBING.. [4] - six Emily ISE 8888

[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

Collision is Detected at the Index:


10
Issue is solved by Linear probing
with the new Index: 11 ..HASH DEMONSTRATION WITH LINEAR
PROBING..
six Emily ISE 8888
1. Insertion
Collision is Detected at the Index:
2 2. Display
Issue is solved by Linear probing
with the new Index: 4 3. Exit

Enter your Choice: 1


Enter your Choice: 2
How many records: 3
Employee details...
Give 3 record details one by one
iNDEX SSN NAME DEPT. SALARY
SSN NAME DEPT. SALARY
[0] - one John CSE 1111
two Kathy ISE 2222
[1] - one John CSE 1111

[2] - four Kathy ECE 4444 Duplicate key: one

[3] - three Brian ISE 5555 Enter your Choice: 3


Exit
ten Jack CSE 7777

..HASH DEMONSTRATION WITH LINEAR


PROBING.. Collision is Detected at the Index:
2
Issue is solved by Linear probing
1. Insertion with the new Index: 5

2. Display Eleven Tim ISE 8888

3. Exit
Collision is Detected at the Index:
Enter your Choice: 1 2

How many records: 14 Issue is solved by Linear probing


with the new Index: 6
Give 14 record details one by one
twelve Roger CSE 9999
SSN NAME DEPT. SALARY
one John CSE 1111
two Kathy CSE 2222 Collision is Detected at the Index:
three Martin ISE 3333 0
four Emily Ise 4444
five Helena ECE 5555 Issue is solved by Linear probing
with the new Index: 1

Collision is Detected at the Index: thirty Sarah ISE 1111


10

Issue is solved by Linear probing Collision is Detected at the Index:


with the new Index: 11 0

six Joan ECE 6666 Issue is solved by Linear probing


with the new Index: 7

Collision is Detected at the Index: fourtyCurry ECE 3333


2
All buckets are occupied
Issue is solved by Linear probing
with the new Index: 4 Enter your Choice: 2

seven DanielCSE 2222 Employee details...


eight Brook ISE 5555
nine Boby ISE 6666 iNDEX SSN NAME DEPT. SALARY

[0] - nine Boby ISE 6666


Collision is Detected at the Index:
10 [1] - twelve Roger CSE 9999
Issue is solved by Linear probing
with the new Index: 0 [2] - four Emily Ise 4444
[3] - three MartinISE 3333

[4] - six Joan ECE 6666

[5] - ten Jack CSE 7777

[6] - eleven Tim ISE 8888

[7] - thirty Sarah ISE 1111

[8] - two Kathy CSE 2222

[9] - eight Brook ISE 5555

[10] - one John CSE 1111

[11] - five HelenaECE 5555

[12] - seven DanielCSE 2222

Enter your Choice: 3


Exit
Program Explanation:

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.

You might also like