Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 1

Linked List Quiz Key

1. Write a ListNode class that will hold Person* as its data, and is used in a class named List. Include
a constructor, and a destructor for the Person*
class ListNode {
Person *person;
ListNode *next;
ListNode(const Person *p, ListNode *n) : next(n)
{
person = new Person(*p);
} // ListNode()
~ListNode()
{
delete person;
} // ~ListNode()
}; // class ListNode
2. Write a printAll() method for the List class that relies on an overloaded << method for Person to print
the contents of the list.
void List::printAll() {
for(ListNode *ptr = head; ptr; ptr = ptr->next)
cout << *(ptr->person);
} // printAll()
3. Assuming that the Person class has a public getName() method, write an insert method for the List
class that keeps the list sorted by the names of the Persons.
void List::insert(const Person *p) {
ListNode *ptr, *prev = NULL;
for(ptr = head; ptr && strcmp(ptr->person->getName(), p->getName()) < 0; ptr = ptr->next)
prev = ptr;
if (prev) // or if (ptr != head)
prev->next = new ListNode(p, ptr);
else
head = new ListNode(p, ptr);
} // insert()

You might also like