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

Tree

implementation of tree

Uploaded by

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

Tree

implementation of tree

Uploaded by

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

Assignment 5: Application of Linear Lists,Stack and Queue

Code Implementation
Part – 1 : Nested linked lists
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// Structure to store book details


typedef struct Book {
char title[100];
char author[100];
int publicationYear;
struct Book* next;
} Book;

// Structure to store genre details and linked list of books


typedef struct Genre {
char genreName[50];
Book* books; // Pointer to the head of book linked list
struct Genre* next;
} Genre;

// Function to create a new book node


Book* createBookNode(char* title, char* author, int publicationYear) {
Book* newBook = (Book*)malloc(sizeof(Book));
strcpy(newBook->title, title);
strcpy(newBook->author, author);
newBook->publicationYear = publicationYear;
newBook->next = NULL;
return newBook;
}

// Insert a book at the front of the list under a specific genre


void insertBookAtFront(Genre* genre, char* title, char* author, int publicationYear) {
Book* newBook = createBookNode(title, author, publicationYear);
newBook->next = genre->books;
genre->books = newBook;
}

// Delete the first book from the list under a specific genre
void deleteBookFromFront(Genre* genre) {
if (genre->books == NULL) {
printf("No books to delete in this genre.\n");
return;
}
Book* temp = genre->books;
genre->books = genre->books->next;
free(temp);
}

// Display all books under a specific genre


void displayBooks(Genre* genre) {
if (genre->books == NULL) {
printf("No books in the %s genre.\n", genre->genreName);
return;
}
Book* current = genre->books;
while (current != NULL) {
printf("Title: %s, Author: %s, Year: %d\n", current->title, current->author, current->publicationYear);
current = current->next;
}
}

// Function to create a new genre node


Genre* createGenreNode(char* genreName) {
Genre* newGenre = (Genre*)malloc(sizeof(Genre));
strcpy(newGenre->genreName, genreName);
newGenre->books = NULL;
newGenre->next = NULL;
return newGenre;
}

// Insert a genre at the front of the genre list


void insertGenreAtFront(Genre** genreList, char* genreName) {
Genre* newGenre = createGenreNode(genreName);
newGenre->next = *genreList;
*genreList = newGenre;
}

// Delete the first genre from the list


void deleteGenreFromFront(Genre** genreList) {
if (*genreList == NULL) {
printf("No genres to delete.\n");
return;
}
Genre* temp = *genreList;
*genreList = (*genreList)->next;

// Free all books under this genre


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

// Display all genres in the library catalog


void displayGenres(Genre* genreList) {
if (genreList == NULL) {
printf("No genres in the catalog.\n");
return;
}
Genre* current = genreList;
while (current != NULL) {
printf("Genre: %s\n", current->genreName);
displayBooks(current); // Display books under each genre
current = current->next;
}
}

// Function to search for a genre by name


Genre* searchGenreByName(Genre* genreList, char* genreName) {
Genre* current = genreList;
while (current != NULL) {
if (strcmp(current->genreName, genreName) == 0) {
return current; // Genre found
}
current = current->next;
}
return NULL; // Genre not found }
// Search for a book by title
Book* searchBookByTitle(Genre* genreList, char* title) {
Genre* currentGenre = genreList;
while (currentGenre != NULL) {
Book* currentBook = currentGenre->books;
while (currentBook != NULL) {
if (strcmp(currentBook->title, title) == 0) {
printf("Book found in genre: %s\n", currentGenre->genreName);
return currentBook;
}
currentBook = currentBook->next;
}
currentGenre = currentGenre->next;
}
printf("Book not found.\n");
return NULL;
}

// Update book details by title


void updateBookDetails(Genre* genreList, char* title, char* newAuthor, int newPublicationYear) {
Book* book = searchBookByTitle(genreList, title);
if (book != NULL) {
strcpy(book->author, newAuthor);
book->publicationYear = newPublicationYear;
printf("Book details updated.\n");
}
}

// User Interface for Library Catalog Management System


void menu(Genre** genreList) {
int choice;
char title[100], author[100], genreName[50];
int year;

do {
printf("\nLibrary Catalog Management System\n");
printf("1. Add Genre\n");
printf("2. Add Book\n");
printf("3. Delete Genre\n");
printf("4. Delete Book\n");
printf("5. Display Catalog\n");
printf("6. Search Book\n");
printf("7. Update Book\n");
printf("8. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
getchar(); // to consume the newline after scanf

switch (choice) {
case 1:
// Add Genre
printf("Enter genre name: ");
fgets(genreName, sizeof(genreName), stdin);
genreName[strlen(genreName) - 1] = '\0'; // remove newline
insertGenreAtFront(genreList, genreName);
break;

case 2:
// Add Book
printf("Enter genre name to add book: ");
fgets(genreName, sizeof(genreName), stdin);
genreName[strlen(genreName) - 1] = '\0';
printf("Enter book title: ");
fgets(title, sizeof(title), stdin);
title[strlen(title) - 1] = '\0';
printf("Enter author: ");
fgets(author, sizeof(author), stdin);
author[strlen(author) - 1] = '\0';
printf("Enter publication year: ");
scanf("%d", &year);
getchar();

Genre* genre = searchGenreByName(*genreList, genreName);


if (genre != NULL) {
insertBookAtFront(genre, title, author, year);
} else {
printf("Genre not found.\n");
}
break;

case 3:
// Delete Genre
printf("Enter genre name to delete: ");
fgets(genreName, sizeof(genreName), stdin);
genreName[strlen(genreName) - 1] = '\0';
if (*genreList != NULL && strcmp((*genreList)->genreName, genreName) == 0) {
deleteGenreFromFront(genreList);
printf("Genre deleted successfully.\n");
} else {
Genre* prev = NULL;
Genre* current = *genreList;
while (current != NULL && strcmp(current->genreName, genreName) != 0) {
prev = current;
current = current->next;
}
if (current != NULL) {
prev->next = current->next;
while (current->books != NULL) {
deleteBookFromFront(current);
}
free(current);
printf("Genre deleted successfully.\n");
} else {
printf("Genre not found.\n");
}
}
break;

case 4:
// Delete Book
printf("Enter genre name to delete book from: ");
fgets(genreName, sizeof(genreName), stdin);
genreName[strlen(genreName) - 1] = '\0';
genre = searchGenreByName(*genreList, genreName);
if (genre != NULL) {
printf("Enter book title to delete: ");
fgets(title, sizeof(title), stdin);
title[strlen(title) - 1] = '\0';
Book* prevBook = NULL;
Book* currentBook = genre->books;
if (currentBook != NULL && strcmp(currentBook->title, title) == 0) {
deleteBookFromFront(genre);
printf("Book deleted successfully.\n");
} else {
while (currentBook != NULL && strcmp(currentBook->title, title) != 0) {
prevBook = currentBook;
currentBook = currentBook->next;
}
if (currentBook != NULL) {
prevBook->next = currentBook->next;
free(currentBook);
printf("Book deleted successfully.\n");
} else {
printf("Book not found.\n");
}
}
} else {
printf("Genre not found.\n");
}
break;

case 5:
// Display Catalog
displayGenres(*genreList);
break;

case 6:
// Search Book
printf("Enter book title to search: ");
fgets(title, sizeof(title), stdin);
title[strlen(title) - 1] = '\0';
Book* foundBook = searchBookByTitle(*genreList, title);
if (foundBook != NULL) {
printf("Book found: %s by %s, Published in %d\n", foundBook->title, foundBook->author, foundBook-
>publicationYear);
}
break;

case 7:
// Update Book
printf("Enter book title to update: ");
fgets(title, sizeof(title), stdin);
title[strlen(title) - 1] = '\0';
printf("Enter new author name: ");
fgets(author, sizeof(author), stdin);
author[strlen(author) - 1] = '\0';
printf("Enter new publication year: ");
scanf("%d", &year);
getchar();
updateBookDetails(*genreList, title, author, year);
break;

case 8:
// Exit
printf("Exiting the Library Catalog Management System.\n");
break;

default:
printf("Invalid choice. Please try again.\n");
break;
}
} while (choice != 8);
}

int main() {
Genre* genreList = NULL;
menu(&genreList);
return 0;
}
Part – 2: Polynomial using linked lists
#include <stdio.h>
#include <stdlib.h>
#include <math.h> // Include math.h to use pow function

// Structure to store a term of a polynomial


typedef struct Term {
int coeff;
int exp;
struct Term* next;
} Term;

// Function to create a new term node


Term* createTerm(int coeff, int exp) {
Term* newTerm = (Term*)malloc(sizeof(Term));
newTerm->coeff = coeff;
newTerm->exp = exp;
newTerm->next = NULL;
return newTerm;
}

// Function to insert a term into a polynomial (sorted by exponent in decreasing order)


void insertTerm(Term** poly, int coeff, int exp) {
Term* newTerm = createTerm(coeff, exp);

// If the list is empty or the exponent is larger than the head, insert at the front
if (*poly == NULL || (*poly)->exp < exp) {
newTerm->next = *poly;
*poly = newTerm;
} else {
Term* current = *poly;
while (current->next != NULL && current->next->exp >= exp) {
if (current->next->exp == exp) {
current->next->coeff += coeff; // If same exponent, add coefficients
free(newTerm);
return;
}
current = current->next;
}
newTerm->next = current->next;
current->next = newTerm;
}
}

// Function to display the polynomial in the correct format


void displayPolynomial(Term* poly) {
if (poly == NULL) {
printf("0\n");
return;
}
int firstTerm = 1; // To handle signs appropriately for the first term
while (poly != NULL) {
if (!firstTerm && poly->coeff > 0) {
printf("+ ");
}

if (poly->exp == 0) {
printf("%d ", poly->coeff);
} else if (poly->exp == 1) {
printf("%dx ", poly->coeff);
} else {
printf("%dx^%d ", poly->coeff, poly->exp);
}

poly = poly->next;
firstTerm = 0;
}
printf("\n");
}

// Function to add two polynomials


Term* addPolynomials(Term* poly1, Term* poly2) {
Term* result = NULL;

while (poly1 != NULL && poly2 != NULL) {


if (poly1->exp > poly2->exp) {
insertTerm(&result, poly1->coeff, poly1->exp);
poly1 = poly1->next;
} else if (poly1->exp < poly2->exp) {
insertTerm(&result, poly2->coeff, poly2->exp);
poly2 = poly2->next;
} else {
insertTerm(&result, poly1->coeff + poly2->coeff, poly1->exp);
poly1 = poly1->next;
poly2 = poly2->next;
}
}

// If remaining terms in either polynomial, add them


while (poly1 != NULL) {
insertTerm(&result, poly1->coeff, poly1->exp);
poly1 = poly1->next;
}
while (poly2 != NULL) {
insertTerm(&result, poly2->coeff, poly2->exp);
poly2 = poly2->next;
}

return result;
}

// Function to multiply two polynomials


Term* multiplyPolynomials(Term* poly1, Term* poly2) {
Term* result = NULL;

for (Term* t1 = poly1; t1 != NULL; t1 = t1->next) {


for (Term* t2 = poly2; t2 != NULL; t2 = t2->next) {
insertTerm(&result, t1->coeff * t2->coeff, t1->exp + t2->exp);
}
}

return result;
}

// Function to evaluate a polynomial for a given value of x


int evaluatePolynomial(Term* poly, int x) {
int result = 0;
while (poly != NULL) {
result += poly->coeff * pow(x, poly->exp);
poly = poly->next;
}
return result;
}

// Function to create a polynomial by prompting the user for input


Term* createPolynomial() {
int n, coeff, exp;
Term* poly = NULL;

printf("Enter the number of terms in the polynomial: ");


scanf("%d", &n);

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


printf("Enter coefficient and exponent for term %d: ", i + 1);
scanf("%d %d", &coeff, &exp);
insertTerm(&poly, coeff, exp);
}

return poly;
}

int main() {
Term* poly1 = NULL;
Term* poly2 = NULL;
Term* result = NULL;
int choice, x;

do {
printf("\nPolynomial Operations Menu\n");
printf("1. Create Polynomial\n");
printf("2. Display Polynomial\n");
printf("3. Add Polynomials\n");
printf("4. Multiply Polynomials\n");
printf("5. Evaluate Polynomial\n");
printf("6. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
printf("Create first polynomial:\n");
poly1 = createPolynomial();
printf("Create second polynomial:\n");
poly2 = createPolynomial();
break;

case 2:
printf("First polynomial: ");
displayPolynomial(poly1);
printf("Second polynomial: ");
displayPolynomial(poly2);
break;
case 3:
result = addPolynomials(poly1, poly2);
printf("Sum of polynomials: ");
displayPolynomial(result);
break;

case 4:
result = multiplyPolynomials(poly1, poly2);
printf("Product of polynomials: ");
displayPolynomial(result);
break;

case 5:
printf("Enter the value of x to evaluate: ");
scanf("%d", &x);
printf("Evaluation of first polynomial: %d\n", evaluatePolynomial(poly1, x));
printf("Evaluation of second polynomial: %d\n", evaluatePolynomial(poly2, x));
break;

case 6:
printf("Exiting...\n");
break;

default:
printf("Invalid choice! Please try again.\n");
}
} while (choice != 6);
return 0;}
Part – 3 : Postfix Expression Evaluation using Stack
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>

// Stack node structure


typedef struct StackNode {
int data;
struct StackNode* next;
} StackNode;

// Stack operations
StackNode* createNode(int data) {
StackNode* newNode = (StackNode*)malloc(sizeof(StackNode));
newNode->data = data;
newNode->next = NULL;
return newNode;
}

int isEmpty(StackNode* root) {


return !root;
}

void push(StackNode** root, int data) {


StackNode* newNode = createNode(data);
newNode->next = *root;
*root = newNode;
}

int pop(StackNode** root) {


if (isEmpty(*root)) {
return -1; // Underflow
}
StackNode* temp = *root;
*root = (*root)->next;
int popped = temp->data;
free(temp);
return popped;
}

int peek(StackNode* root) {


if (isEmpty(root)) {
return -1; // Underflow
}
return root->data;
}

// Function to evaluate a postfix expression


int evaluatePostfixExpression(char* exp) {
StackNode* stack = NULL;
int i;

for (i = 0; exp[i]; i++) {


// If the character is a space, skip it
if (exp[i] == ' ') {
continue;
}

// If the character is a digit, push it to the stack


else if (isdigit(exp[i])) {
int num = 0;

// There may be more than one digit in a number


while (isdigit(exp[i])) {
num = num * 10 + (exp[i] - '0');
i++;
}
i--; // Adjust for next iteration
push(&stack, num);
}

// If the character is an operator, pop two elements and apply the operator
else {
int val1 = pop(&stack);
int val2 = pop(&stack);

switch (exp[i]) {
case '+':
push(&stack, val2 + val1);
break;
case '-':
push(&stack, val2 - val1);
break;
case '*':
push(&stack, val2 * val1);
break;
case '/':
push(&stack, val2 / val1);
break;
}
}
}
// The final result will be at the top of the stack
return pop(&stack);
}

// Function to return precedence of operators


int precedence(char op) {
if (op == '+' || op == '-')
return 1;
if (op == '*' || op == '/')
return 2;
return 0;
}

// Function to check if the character is an operator


int isOperator(char c) {
return (c == '+' || c == '-' || c == '*' || c == '/');
}

// Function to convert infix expression to postfix expression


void convertInfixToPostfix(char* infix, char* postfix) {
StackNode* stack = NULL;
int i, j = 0;

for (i = 0; infix[i]; i++) {


// If the character is an operand, add it to the output
if (isdigit(infix[i])) {
while (isdigit(infix[i])) {
postfix[j++] = infix[i++];
}
postfix[j++] = ' ';
i--;
}
// If the character is '(', push it to the stack
else if (infix[i] == '(') {
push(&stack, infix[i]);
}
// If the character is ')', pop and output until '(' is found
else if (infix[i] == ')') {
while (!isEmpty(stack) && peek(stack) != '(') {
postfix[j++] = pop(&stack);
postfix[j++] = ' ';
}
pop(&stack); // Remove '(' from stack
}
// If the character is an operator
else if (isOperator(infix[i])) {
while (!isEmpty(stack) && precedence(infix[i]) <= precedence(peek(stack))) {
postfix[j++] = pop(&stack);
postfix[j++] = ' ';
}
push(&stack, infix[i]);
}
}

// Pop all the remaining operators from the stack


while (!isEmpty(stack)) {
postfix[j++] = pop(&stack);
postfix[j++] = ' ';
}
postfix[j] = '\0'; // Null terminate the string
}

// Main function to test the program


int main() {
char infix[100], postfix[100];
int choice;

while (1) {
printf("\nMenu:\n");
printf("1. Evaluate Postfix Expression\n");
printf("2. Convert Infix to Postfix and Evaluate\n");
printf("3. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
getchar(); // To consume the newline character left by scanf

switch (choice) {
case 1: {
char postfixExp[100];
printf("Enter a postfix expression: ");
fgets(postfixExp, 100, stdin);
postfixExp[strcspn(postfixExp, "\n")] = 0; // Remove trailing newline
printf("Result: %d\n", evaluatePostfixExpression(postfixExp));
break;
}
case 2: {
printf("Enter an infix expression: ");
fgets(infix, 100, stdin);
infix[strcspn(infix, "\n")] = 0; // Remove trailing newline

convertInfixToPostfix(infix, postfix);
printf("Postfix expression: %s\n", postfix);
printf("Result: %d\n", evaluatePostfixExpression(postfix));
break;
}
case 3:
exit(0);
default:
printf("Invalid choice!\n");
}
}

return 0;
}
Part – 4 : Hot Potato Game Simulation using Queues

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

// Queue node structure


typedef struct QueueNode {
char name[100];
struct QueueNode* next;
} QueueNode;

// Queue structure
typedef struct Queue {
QueueNode* front;
QueueNode* rear;
} Queue;

// Function to create a new queue node


QueueNode* createNode(char* name) {
QueueNode* newNode = (QueueNode*)malloc(sizeof(QueueNode));
strcpy(newNode->name, name);
newNode->next = NULL;
return newNode;
}

// Function to create an empty queue


Queue* createQueue() {
Queue* q = (Queue*)malloc(sizeof(Queue));
q->front = q->rear = NULL;
return q;
}

// Function to check if the queue is empty


int isEmpty(Queue* q) {
return q->front == NULL;
}

// Function to enqueue a player (add to the rear of the queue)


void enqueuePlayer(Queue* q, char* name) {
QueueNode* newNode = createNode(name);
if (isEmpty(q)) {
q->front = q->rear = newNode;
} else {
q->rear->next = newNode;
q->rear = newNode;
}
newNode->next = q->front; // Circular linking
}

// Function to dequeue a player (remove from the front of the queue)


char* dequeuePlayer(Queue* q) {
if (isEmpty(q)) {
return NULL;
}

QueueNode* temp = q->front;


char* name = (char*)malloc(100 * sizeof(char));
strcpy(name, temp->name);

// If only one node in the queue


if (q->front == q->rear) {
q->front = q->rear = NULL;
} else {
q->front = q->front->next;
q->rear->next = q->front; // Circular linking
}

free(temp);
return name;
}

// Function to simulate the Hot Potato game


void playHotPotato(Queue* q, int passCount) {
while (q->front != q->rear) { // Until only one player remains
// Pass the potato passCount times
for (int i = 0; i < passCount; i++) {
q->rear = q->front; // Move rear pointer to the current front
q->front = q->front->next; // Move front pointer to the next node (pass the potato)
}
// Eliminate the player holding the potato
char* eliminatedPlayer = dequeuePlayer(q);
printf("Player eliminated: %s\n", eliminatedPlayer);
free(eliminatedPlayer);
}
printf("The winner is: %s\n", q->front->name);
}

int main() {
Queue* q = createQueue();
int numPlayers, passCount;

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


scanf("%d", &numPlayers);
getchar(); // To consume the newline character

// Input player names


for (int i = 0; i < numPlayers; i++) {
char playerName[100];
printf("Enter player %d name: ", i + 1);
fgets(playerName, 100, stdin);
playerName[strcspn(playerName, "\n")] = 0; // Remove the newline character
enqueuePlayer(q, playerName);
}
// Input pass count
printf("Enter the number of passes before eliminating a player: ");
scanf("%d", &passCount);

// Start the Hot Potato game


playHotPotato(q, passCount);

return 0;
}
Sample and Significant Outputs
Part 1
Library Catalog Management System
1. Add Genre
2. Add Book
3. Delete Genre
4. Delete Book
5. Display Catalog
6. Search Book
7. Update Book
8. Exit
Enter your choice: 1
Enter genre name: news

Library Catalog Management System


1. Add Genre
2. Add Book
3. Delete Genre
4. Delete Book
5. Display Catalog
6. Search Book
7. Update Book
8. Exit
Enter your choice: 2
Enter genre name to add book: news
Enter book title: first
Enter author: A.K.S
Enter publication year: 2024
Part 2
Polynomial Operations Menu
1. Create Polynomial
2. Display Polynomial
3. Add Polynomials
4. Multiply Polynomials
5. Evaluate Polynomial
6. Exit
Enter your choice: 1
Create first polynomial:
Enter the number of terms in the polynomial: 2
Enter coefficient and exponent for term 1: 12 3
Enter coefficient and exponent for term 2: 23 2
Create second polynomial:
Enter the number of terms in the polynomial: 2
Enter coefficient and exponent for term 1: 3 5
Enter coefficient and exponent for term 2: 3 3
Polynomial Operations Menu
1. Create Polynomial
2. Display Polynomial
3. Add Polynomials
4. Multiply Polynomials
5. Evaluate Polynomial
6. Exit
Enter your choice: 2
First polynomial: 12x^3 + 23x^2
Second polynomial: 3x^5 + 3x^3
Polynomial Operations Menu
1. Create Polynomial
2. Display Polynomial
3. Add Polynomials
4. Multiply Polynomials
5. Evaluate Polynomial
6. Exit
Enter your choice: 3
Sum of polynomials: 3x^5 + 15x^3 + 23x^2
Part 3
Menu:
1. Evaluate Postfix Expression
2. Convert Infix to Postfix and Evaluate
3. Exit
Enter your choice: 1
Enter a postfix expression: 5 6 2 + *
Result: 40
1. Evaluate Postfix Expression
2. Convert Infix to Postfix and Evaluate
3. Exit
Enter your choice: 2
Enter an infix expression: (5 + 6) * 2
Postfix expression: 5 6 + 2 *
Result: 22
Part 4
Enter the number of players: 2
Enter player 1 name: abh
Enter player 2 name: bhi
Enter the number of passes before eliminating a player: 3
Player eliminated: bhi
The winner is: abh

You might also like