C++ Linked Lists   «Prev  Next»

Modifying C++ Singly linked list - Exercise Result

Modifying Singly Linked List implementation

Objective: Modify slist::del() to test for an empty list, add a constructor to slistelem to simplify coding of a member function, and add a new member function that appends a list to a list.


This is a three-part exercise that involves modifying the implementation of slist. The original code for slist is also available in a file named slist.cpp, which can be found in the compressed course download file available on the Resources page.
Modify the slist::del() to test for an empty list.
If the list is empty, continue processing. As written, slist::del() expects a non-empty list. This can cause problems if the list is empty. You could use assert to test for an empty list, but this will cause the program to abort.
Add a constructor to slistelem and use it to simplify the coding of the prepend() member function.
If we have a constructor for slistelem, the prepend() member function could be simplified like this:

void slist::prepend(char c)
   slistelem* temp = new slistelem(c, h);  //create element
   h = temp;

Notice that the new of slistelem(c, h) calls the constructor to initialize the c and h variables. Write a member function append that will add a list to the end of the implicit list argument (i.e., the original list), then clear the appended list by zeroing the head.
You will also need to write a function unhook to zero the head.
void slist::append(slist& e);
void slist::unhook() { h = 0; }

Paste the source code of the slist class and its external member functions below and click the Submit button when you are ready to submit this exercise.