X505: Count Linked Nodes

Consider the following class definition for a Node class:

class Node<T> {
  private T data;
  private Node next;
  public Node(T d) { data = d; next = null; }
  public Node(T d, Node n) { data = d; next = n; }
  public T getData() { return data; }
  public Node<T> getNext() { return next; }
  public void setNext(Node<T> n) { next = n; }
}

Write a method countNodes() that when given a list that starts at the node pointed by p, returns the number of nodes in the list. Note that if p is null (empty list), your method should return 0.

In the first example below the following Node client code builds a linked list of two nodes, "A" and "B". The countNodes() call on line 2 returns 2.

Node<String> l = new Node<>("A", new Node("B"));
int count = countNodes(l)  // returns 2

This second example builds a list by hand. The countNodes() call on line 6 returns a count of 3.

Node<String> a = new Node<>("A");
Node<String> b = new Node<>("B");
Node<String> c = new Node<>("C");
a.setNext(b);
b.setNext(c);
int count = countNodes(a);

Write the countNodes() method. Note that the examples all use String for the type, but this is a generic method that should work for any data type.

Your Answer:

Feedback

Your feedback will appear here when you check your answer.