#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #ifdef…
- User
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h>
#ifdef _WIN32 #include <string.h> #define strcasecmp _stricmp #endif
// Define maximum lengths for strings #define MAX_TITLE 256 #define MAX_AUTHORS 256 #define MAX_GENRE 100 #define MAX_LINE 1024
typedef struct Book { char title[MAX_TITLE]; char authors[MAX_AUTHORS]; int year; double rating; double price; char genre[MAX_GENRE]; } Book;
typedef struct AVLNode { Book book; struct AVLNode* left; struct AVLNode* right; int height; } AVLNode;
// Enum for command types typedef enum { CMD_ADD, CMD_DELETE, CMD_SEARCH, CMD_EDIT, CMD_LNRPRINTTREE, CMD_NLRPRINTTREE, CMD_LRNPRINTTREE, CMD_HELP, CMD_INVALID } CommandType;
// Function prototypes int max_int(int a, int b); int height_node(AVLNode* N); AVLNode* newNode(Book book); AVLNode* rightRotate(AVLNode* y); AVLNode* leftRotate(AVLNode* x); int getBalance(AVLNode* N); int compareBooks(const Book* a, const Book* b); AVLNode* insertNode(AVLNode* node, Book book, int* added); AVLNode* minValueNode(AVLNode* node); AVLNode* deleteNode(AVLNode* root, char* title, int* deleted); int searchTree(AVLNode* root, char* field, char* value); void inorderTraversal(AVLNode* root); void preorderTraversal(AVLNode* root); void postorderTraversal(AVLNode* root); void printBook(Book book); void trim(char* str); CommandType identify_command(const char* input_line); int compare_nocase(const char* a, const char* b, size_t n); void handle_add(AVLNode** root); void handle_delete(AVLNode** root, char* params); void handle_search(AVLNode* root, char* params); void handle_edit(AVLNode** root); void handle_lnrprinttree(AVLNode* root); void handle_nlrprinttree(AVLNode* root); void handle_lrnprinttree(AVLNode* root); void handle_help(); void free_avl_tree(AVLNode* root);
// Implementations
// Helper function for case-insensitive comparison int compare_nocase(const char* a, const char* b, size_t n) { for (size_t i = 0; i < n; i++) { char ca = tolower((unsigned char)a[i]); char cb = tolower((unsigned char)b[i]); if (ca != cb) return ca - cb; if (ca == '\0') return 0; } return 0; }
int max_int(int a, int b) { return (a > b) ? a : b; }
int height_node(AVLNode* N) { if (N == NULL) return 0; return N->height; }
AVLNode* newNode(Book book) { AVLNode* node = (AVLNode*)malloc(sizeof(AVLNode)); if (!node) { perror("Failed to allocate memory"); exit(EXIT_FAILURE); } node->book = book; node->left = node->right = NULL; node->height = 1; // New node is initially added at leaf return node; }
AVLNode* rightRotate(AVLNode* y) { AVLNode* x = y->left; AVLNode* T2 = x->right;
code// Perform rotation x->right = y; y->left = T2; // Update heights y->height = max_int(height_node(y->left), height_node(y->right)) + 1; x->height = max_int(height_node(x->left), height_node(x->right)) + 1; // Return new root return x; - Assistant