CSCI 159: exam practice sample answers
The program below is used as the basis for both question 1 and question 2. It maintains a linked list of names and identifiers: getting names/ids from
the user until the user enters "q" instead of a name, then printing out the list contents.
#include <iostream>
#include <string>
using namespace std;
struct item {
string name;
int id;
item* next;
};
int main()
{
item* front = nullptr;
string person;
do {
cout << "Enter the name of the next person, e.g. Luthor, or q to quit" << endl;
cin >> person;
if (person != "q") {
int personid;
cout << "Enter an integer id for " << person << ": " << endl;
cin >> personid;
item* i = new (std::nothrow) item;
if (i != nullptr) {
i->next = front;
front = i;
i->name = person;
i->id = personid;
}
}
} while (person != "q");
item* current = front;
while (current != nullptr) {
cout << current->name << " " << current->id << endl;
current = current->next;
}
//Sample answer
current = front;
while (current != nullptr) {
item* ItemToBeDeleted = current;
current = current->next;
delete ItemToBeDeleted;
}
front = nullptr; // for safety/clarity
}
Question 1: Basic linked lists: deleting
Just before the end of the main routine (i.e. after all the prints have been completed),
add a loop that deallocates each of the items in the list. (Don't rewrite the whole main
routine, just the new loop and an arrow to where it goes.)
Question 2: Basic linked lists: insert function
Write an insert function for the program above that could be called from the loop in the
main routine, so that using insert the do-while loop in main would look more like
do {
cout << "Enter the name of the next person, e.g. Luthor, or q to quit" << endl;
cin >> person;
if (person != "q") {
int personid;
cout << "Enter an integer id for " << person << ": " << endl;
cin >> personid;
insert(person, personid, front);
}
} while (person != "q");
//Sample answer
// note that front needs to be passed by reference so we can update it
void insert(string pname, int pid, item* &front)
{
item* current = new (std::nothrow) item;
if (current != nullptr) {
current->next = front;
front = current;
current->name = pname;
current->id = pid;
}
}