can someone tell me how do I termninated and freelist in linked list? Can I use
ID: 3696682 • Letter: C
Question
can someone tell me how do I termninated and freelist in linked list? Can I use pointer and substring?
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.
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. void terminateWrite (struct book * head);
If the user enter this command you are to write all the books in the list to a file called Booklist.txt. All fields of the structure for each book should be written to an individual line. After writing you should call freeList and then the program will terminate.
2. struct book * freeList(struct book * head);
Here you should free all the elements of your list and return NULL to main.
Explanation / Answer
Here is the code for you:
void terminateWrite (struct book * head)
{
ofstream fout;
struct book *temp = head;
fout.open("Booklist.txt"); //Opens the file.
while(head != NULL) //Till the last node.
{
fout<<head->ID<<" "<<head->Title<<" "<<head->Author<<" "<<head->SubjectCode<<" "<<head->BorrowingAge<<" ";
fout<<head->BorrowingName<<endl; //Write the data to a line, and move on to the next line.
head = head->next; //Move to next node.
}
fout.close(); //After writing all the nodes, close the file.
freeList(temp); //Call the freeList() to free the nodes.
}
struct book * freeList(struct book * head)
{
struct book *temp; //Creates a temporary pointer.
while(head != NULL) //Till the last node.
{
temp = head; //Copy the first node address to temp.
head = head->next; //Move to next node.
free(temp); //Free the previous node.
}
return NULL; //As all nodes are deleted, you've nothing to return.
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.