12.7 Avoiding Errors and Debugging

Avoiding Errors

  1. Always check that your algorithms work for special cases such as empty lists and lists that have only one node. These can often cause problems because they may have to be handled slightly differently from other cases.
  2. It is usually a good idea to avoid use of references with identifiers like current . link . link. If you have to look more than one place along a list, it is almost always better to use auxiliary variables with descriptive identifiers such as previous or next.

Debugging

  1. The order in which reference values are assigned is almost always crucial to the success of a method involving links. If a method is not behaving correctly, use diagrams to help you in determining which references should be changed and in what order those changes should occur.
  2. In attempting to debug a program involving linked data structures, it is often difficult to tell where the problem is occurring - in the building of the structure or in the manipulation of a properly constructed list or tree. To try to isolate a problem, it may be useful to build a simple structure "by hand" and then test any manipulation methods on this list. As an example, a linked list (of our usual type) containing three nodes could be created by the following constructor for the List class.

    public List (int m, int n, int p)
    {
       head = new Node(m,null);
       head.link = new Node(n,null);
       head. link. link = new Node(p,null);
    }

Exercises 12.7

  1. The following fragment is intended to print the contents of a linked list like the ones discussed in this chapter. What is wrong with the fragment?
    Node temp = head;
    do
    {
       System.out.println(temp.info);
       temp = temp.link;
    }
    while (temp != null); 
  2. Write a constructor for the Tree class discussed in this chapter. The constructor should have three int parameters: a, b, and c. It should construct the tree shown in the diagram.
  3. Write a fragment that will create a new node containing the value 27 in its info field and then insert this node into the list between the two nodes shown in the diagram.