// Lab Sheet 5 Example A (Class-based solution to Lab Problem 4.1) // CS211 ADS2 // T Naughton, CS NUIM #include /* This program reads positive integers, one per line, from the ** keyboard into a list. The user indicates that they are finished ** by entering any negative integer (the negative integer itself is ** not stored). The computer program then prints out the list of ** numbers, on a single line, separated with blank spaces. This ** program uses classes and a linked list. */ class ListElement { // A very simple class describing each node of the list public: int element; ListElement * next; }; class IntList { ListElement * head; // a pointer to the head of the list public: IntList(); // constructor ~IntList(); // destructor // methods that act on IntList void AddtoFront(int newdata); void PrintList(); }; IntList::IntList() { head = NULL; // Initialise the list (mark the end of the list // with NULL). } IntList::~IntList() { // The entire list should be deleted here } void IntList::AddtoFront(int newdata){ // This function creates a new node with that data that is passed to // it, adding the node to the front of the list. ListElement * temp; // Create a pointer to a new node temp = new ListElement; // Allocate memory for the node temp->element = newdata; // Put the data in the node // Put this node at the top of the list by (a) pointing it at the // head of the list and (b) repointing the head of the list at this // node. // Can you see that the first time we add a node to the list // (i.e. when head==NULL) that we end up marking the end of the // list with a NULL? temp->next = head; head = temp; } void IntList::PrintList(){ // This function prints out the list. It does so by printing out the // contents of the head of the list and then each subsequent element // in turn. It repeats this until the end of the // list (a NULL) is found. The function returns a pointer to the // head of the list. Note: this function will work if an empty // list is passed to it. ListElement * current; current = head; // set current to point to the head of the list cout << endl << endl << "Here's the list:" << endl; while (current != NULL) { cout << current->element << ' '; current = current->next; } } void main(void){ IntList list; int tempint; // temporary storage for ints from user cout << endl << endl << "Please enter positive integers (one "; cout << "per line). Terminate with any negative integer:" << endl; cin >> tempint; while (tempint >= 0) { list.AddtoFront(tempint); cin >> tempint; } list.PrintList(); }