Homework Solution

Singly Linked Lists and Circular Lists

Problems to be Submitted (20 points)

  1. (7 points)
    template <typename Object>
    void LinkedStack<Object>::~LinkedStack() {
      while (head != NULL) {
          Node* old = head;
          head = head->next;
          delete old;
      }
    }
    
  2. (7 points)
    template <typename Object>
    void LinkedQueue<Object>::size() const {
      int count=0;
      if (cursor != NULL) {
          Node* walk = cursor->next;
          count++;
          while (walk != cursor) {
              walk = walk->next;
              count++;
          }
      }
      return count;
    }
    
  3. (6 points)

    As it turns out, the class would function perfectly well with the simplification. There are two issues worth noting. First, in the case where old == cursor, switching to the action cursor->next = old->next is somewhat irrelevant since that node is about to be deleted anyway. The other impact of the change is that the cursor variable is not set back to NULL to represent the empty queue. Intuitively, it seems cleaner to have that variable set back to NULL rather than leaving it as a pointer value to a node that doesn't even exist anymore. But this doesn't effect the logic, because so long as n=0, the logic dictates that the value of the cursor variable is never examined.


Last modified: Tuesday, 13 October 2015