Hi guys! I am currently having trouble in the final stages of an assignment which involves linked lists and dynamic arrays. The assignment involves adding books to a library. This means that each record has a title and one or more authors. I have worked out what I think was the hard part, which was how to add the title and authors. However, I have run into a problem when it comes time to print the books by book title. The specs require that when all the books are printed they are printed by book sorted in alphabetical order. I am not sure how best to do this. Should I sort the linked list or should I sort them as I add them and if so how do I do this?
Here is the header file:
class Library{
public:
Library();
/*Library(const Library &other);
Library &operator=(const Library &other);
~Library(); */
void add(string title, string authors[], int nAuthors);
void print() const;
void printByAuthor(string author) const;
private:
struct book
{
string title;
string *author;
book *link;
int numAuthors;
} *p;
};
Please note: the copy constructor and operator overload form part of a bonus, which I am not concerned with at this stage. My function to add a book is as follows:
void Library::add(string title, string authors[], int nAuthors)
{
// new node required
book *q, *t;
if (p == NULL)
{
p = new book;
p->title = title;
p->author = new string[nAuthors];
for (int i = 0; i < nAuthors; i++)
p->author[i] = authors[i];
p->link = NULL;
p->numAuthors = nAuthors;
}
else
{
q = p;
while (q->link != NULL)
q = q->link;
t = new book;
t->title = title;
t->author = new string[nAuthors];
for (int i = 0; i < nAuthors; i++)
t->author[i] = authors[i];
t->link = NULL;
q->link = t;
t->numAuthors = nAuthors;
}
}
Finally, as it currently stands this my print function:
void Library::print() const
{
book *q;
for (q = p; q != NULL; q = q->link)
{
cout << "Title: " << q->title << endl;
for (int i = 0; i < q->numAuthors; i++)
{
cout << "Author " << i + 1 << ": " << q->author[i] << endl;
}
cout << endl;
}
}
I really feel like I am close, and that this problem can be rectified. Any help you guys might be able to offer would be greatly appreciated.
Cheers,
Daniel