Chapter 16 Exercise Set 1

  1. By convention, lists are printed with parentheses with commas between the elements, as in (1, 2, 3). Modify the print_list function from Lists as collections so that it generates output in this format.

  2. Rewrite print_list using a for loop instead of a while loop.

  3. The function remove_second presented in Modifying linked lists will crash if passed a singleton or empty list. Fix it so that it returns a NULL in these cases instead.

  4. Add a modifier function to the templated LinkList class named insert_at_end(T value) that inserts a new node with cargo value, value, at the end of the list. Modify the LinkedList class to give it a new instance variable, tail, that points to the last node in list. Change insert_at_end to make use of tail.

  5. Add a modifier function to the templated LinkList class named insert_at(T value, int pos) that inserts a new node with cargo value, value, at position pos. pos should be the zero-based position of the new node after insertion, so pos equal to 0 will insert in front, and pos equal to 1 will insert the new node between the first and second (“zeroth” and “oneth”) nodes.

  6. Add a modifier function to the templated LinkList class named insert_in_order that inserts a new node in a list of ordered nodes in the correct order, between the cargo value that proceeds it and the cargo value that succeeds it.

  7. Add a modifier function to the templated LinkList class named remove_from_end that removes the node at end of the list and returns its cargo value. Be sure not to leak memory as you do this!

  8. Add a modifier function to the templated LinkList class named remove_at(int pos) that removes the node at zero-based position pos and returns its cargo value. Again be careful not to leak memory.

  9. Add a member function named find(T value) that returns the number of the first node (starting with 0) in the list with cargo equal to value. find should return -1 if value is not found in the list.

  10. Overload find with a second paramenter, start that returns the number of the first node (starting with start) in the list with cargo equal to value. find(T value, int start) should return -1 if value is not found between start and the end of the list.