CSE 143, Quiz 4                                                     13 Jul 2000

name ____________________________________________ student number _______________

                                                         section _______________

You have eight minutes to complete this quiz.  Write your answers on this page.

1.  For this problem, type Node is defined as follows:

      struct Node {
        int item;
        Node *next;
      };

    Assume that prev is declared as a Node pointer, i.e. type Node *, and that
    prev is initialized as shown in the diagram below, pointing into a linked
    list.
    Write a code fragment which properly deletes the node containing
    value 2.  You are not permitted to declare any variables other
    than temp, which is declared below:

      Node *temp;

      // one way to do it
      temp = prev->next;
      prev->next = prev->next->next;  // splice, then...
      delete temp;                    // delete

      // another way to do it
      temp = prev->next->next;
      delete prev->next;  // delete, then...
      prev->next = temp;  // splice

      // (By "splice", I mean linking nodes in a list together.)


2.  Given the code fragment below, for each line with a comment,
    circle ML if the line causes a memory leak, DP if the line causes
    a dangling pointer, or OK if neither is the case.

      Node *ptr1 = new Node;
      Node *ptr2 = NULL;

      ptr2 = ptr1;            // OK
      delete ptr1;            // DP (ptr2 is left dangling)
      ptr1 = new Node;        // OK
      ptr1 = new Node;        // ML (Node allocated in above line is lost)