Manage database with Linked List Flashcards
How to define node structure?
include <stdio.h></stdio.h>
#include <stdlib.h>
#include <string.h></string.h></stdlib.h>
// define node structure
struct Node
{
int id;
char title[x or 100]
char author[x or 100]
struct Node* next;
};
How to add items to linked list?
struct Node* addItem(struct Node* last, int id, char* title, char* author)
{
// create new node
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode -> id = id;
strcpy(newNode -> title, title);
strcpy(newNode -> author, author);
if (last == NULL)
{
newNode -> next = newNode;
return newNode;
}
newNode -> next = last-> next;
last -> next = newNode;
return newNode;
}
Search for item by title
struct Node* searchItem(struct Node* last, char* title)
{
if (last == NULL)
{
printf(“List is empty.\n”);
return NULL;
}
struct Node* current = last -> next;
do
{
if (strcmp(current->title , title) == 0)
{
return current;
}
current = current->next;
}
while (current != last -> next);
return NULL;
}
How to delete item by ID?
struct Node* deleteItem(struct Node* last, int id)
{
if (last == NULL)
{
printf(“List is empty.\n”);
return NULL;
}
struct Node* current = last->next;
struct Node* prev = last;
//traverse the list
do
{
if (current == last && current -> next == last)
{
free(current)
return NULL;
}
if (current == last)
{
last = prev;
}
prev->next = current->next;
free(current);
return last;
}
prev = current;
current = current->next;
}
while (current != last->next);
printf(“Item with ID %d not found. \n”, id);
return last;
}
How to show all items in list?
// display list
void displayList(struct Node* last)
{
if (last == NULL)
{
printf(“List of empty. \n”);
return;
}
struct Node* = current last->next;
do
{
printf(“ID: %d, Title: %s, Author: %s\n”, current->id, current->title, current->author);
current = current->next;
}
while (current != last->next);
}
Main function database linked list
int main()
{
struct Node* last = NULL;
// add items to list
last = addItem(last, 1, book, author);
last = addItem(last, 2, book, author);
last = addItem(last, 3, book, author);
//display list
printf(“Library Collection:\n”);
displayList(last);
// search for item by title
char searchTitle[100] = “title”;
struct Node* found = searchItem(last, search Title);
if (found != NULL)
{
printf(“\nFound Book: \nID: %d, Title: %s, Author: %s\n”, found->id, found->title, found->author);
}
else
{
printf(“\nBook titled ‘%s’ not found.\n”, searchTitle);
}
// delete item by ID
printf(“\nDeleting book with ID 2…\n);
last = deleteItem(last, 2);
//display list again
printf(“\nUpdated Library Collection:\n)(
displayList(last);
return 0;
}