Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #define SIZE 10 // Size of the dictionary
- int hash(int elem) {
- return elem % SIZE;
- }
- void initDic(Dictionary dict) {
- for (int i = 0; i < SIZE; i++) {
- dict[i] = NULL; // Set all cells to NULL (empty)
- }
- }
- void displayDic(Dictionary dict) {
- for (int i = 0; i < SIZE; i++) {
- printf("Group %d: ", i);
- cellPtr temp = dict[i];
- while (temp != NULL) {
- printf("%5d ", temp->elem); // Print element with padding
- temp = temp->next; // Move to the next node
- }
- printf("\n");
- }
- }
- void insert(Dictionary dict, int elem) {
- int index = hash(elem); // Get the hash value (group number)
- // Check if the element already exists
- cellPtr temp = dict[index];
- while (temp != NULL) {
- if (temp->elem == elem) {
- printf("Element %d already exists in the dictionary.\n", elem);
- return;
- }
- temp = temp->next;
- }
- // Insert the element at the start of the linked list (chaining)
- cellPtr newNode = (cellPtr)malloc(sizeof(struct cell));
- newNode->elem = elem;
- newNode->next = dict[index];
- dict[index] = newNode;
- }
- void populateDic(Dictionary dict, int elements[], int size) {
- for (int i = 0; i < size; i++) {
- insert(dict, elements[i]);
- }
- }
- void deleteElement(Dictionary dict, int elem) {
- int index = hash(elem); // Get the hash value (group number)
- cellPtr temp = dict[index], prev = NULL;
- while (temp != NULL) {
- if (temp->elem == elem) {
- if (prev == NULL) {
- dict[index] = temp->next; // Remove head of the list
- } else {
- prev->next = temp->next; // Bypass the node
- }
- free(temp); // Free memory
- printf("Element %d removed from the dictionary.\n", elem);
- return;
- }
- prev = temp;
- temp = temp->next;
- }
- printf("Element %d not found in the dictionary.\n", elem);
- }
- int isMember(Dictionary dict, int elem) {
- int index = hash(elem);
- cellPtr temp = dict[index];
- while (temp != NULL) {
- if (temp->elem == elem) {
- return 1; // Element found
- }
- temp = temp->next;
- }
- return 0; // Element not found
- }
Advertisement
Add Comment
Please, Sign In to add comment