< Back

Lecture 27 - Linked Lists


As usual, create a directory to hold today's activities:

  $ mkdir ~/cs170/labs/lab27 
  $ cd ~/cs170/labs/lab27 

Iteration

As normal, in computer science we worry about efficiency a lot.


Lab Activity 1
Get Nth

One way that we can iterate over every element of a linked list is to request individual elements out of the list. You can accomplish this by writing a method to your Linked List called getNth

Details

Write a new method of your linked list class called getNth. This method takes one paramters, an integer in the range \([0, numElements)\), and returns an integer (the data contained in the Nth node contained in the linked list.

Make sure you test your methods carefully. Think about what the edge cases are, and how to handle them appropriately.

Test Program


Lab Activity 2
Iterators

The above method makes it possible to iterate over the entirety of the list. However, it is slightly less efficient. It takes \(O(n^2)\) time to iterate over the linear list. Which is not good at all. A different solution is to create an Iterator for the linked list, which will allow the user to iterate over the list, sequentially in one direction, in \(O(n)\) time.

Details

Write a new method of your linked list class called iterator(). This method takes no parameters. It returns a LinkedListIterator object, which can be used to iterate over the elements of the list.

In addition to this new method, you need to implement the LinkedListIterator class. It is ok to write this code in the same file as your LinkedList class. This class must(!) define at least two methods:

Make sure you test your methods carefully. Think about what the edge cases are, and how to handle them appropriately.

Test Program

Uncomment the testIterator function definition and calls