CSCI 159: exam practice questions
These are just meant as a way to get some practice answering
exam-style questions with pen/paper. I'd encourage students
to attempt them with minimal references to their notes, but
for the final exam you will be permitted one double-sided
sheet of notes.
There is one question on each side of the page.
After you've attempted the question, a good way to evaluate your answer
while also getting additional practice is to coding and compiling/running
the answer you came up with.
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;
}
}
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");