How do we generate malloc() struct book and call assignData.? Library Book Manag
ID: 3697122 • Letter: H
Question
How do we generate malloc() struct book and call assignData.?
Library Book Management System will be based on the data type struct book as defined below.
struct book{
int ID;
char Title[50];
char Author[50];
int SubjectCode;
int BorrowingAge;
char BorrowerName[50];
struct book *nextbook;
};
Each book that is in the library list will have a ID, Title, Author Name, Subject Code, Borrowing Age (reflects the number of days passed after it has been borrowed from the library), name of the Borrower and a pointer nextBook which points to a struct book.The code you are writing will need to be placed in prj1.c
Subject code for different subjects as follows:
000 – General works, Computer science and Information, 100 – Philosophy and psychology, 200 – Religion, 300 – Social sciences, 400 – Language, 500 – Pure Science, 600 – Technology, 700 – Arts & recreation, 800 – Literature, 900 – History & geography.
1. struct book * addNewbook (struct book * head);
Here you are to use malloc() to generate a struct book and call assignData that will assign all the info for this new book. You should add the book into the link list. New books should go into the list so that the list is sorted according to ID.
prj1.c. file
Explanation / Answer
Here is the code for you:
struct book * addNewbook (struct book * head)
{
struct book newBook = (struct book *)malloc(sizeof(struct book)); //Creates a new book.
assignData(newBook); //This function assigns the data to newBook.
if(head == NULL) //If there are no nodes in the list.
head = newBook; //Add this node as the first node.
else if(head->ID > newBook->ID) //If this node ID is less than, the first node ID.
{
newBook->next = head; //Copy the first node address into head->next.
head = newBook; //Add this node as the first node.
}
else
{
struct book *temp = head; //Copy the address of head node to temp, to move further.
while(temp->next != NULL && temp->next->ID < newBook->ID) //Keep traversing, till there is no next node, or next node ID is greater than new Node ID.
temp = temp->next; //Move on to the next node.
if(temp->next == NULL) //If next node is NULL, which means, the new node is with largest ID.
temp->next = newBook; //Add the newBook at the end.
else //If not.
{
newBook->next = temp->next; //Copy the next node address to newBook->next.
temp->next = newBook; //Add the newBook as the next node.
}
}
return head;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.