CS160

Assignment #2

DUE : Thursday 9/23.


  1. This first part is essentially exercises 3.13 and 3.14, to implement ListIterators for the MyArrayList and MyLinkedList classes. The interface for ListIterator can be found here. To get this right, you will need to take the following into account (the discussion is in terms of the linked list class, but it's essentially the same as for the array list class):
  2. Now let's actually use the fact that we have a list that you can navigate in both directions. Implement an algorithm (to be sketched in class) that determines if an expression of parentheses is properly balanced (one can do this with a stack, but I'll show you a pretty natural algorithm based on a two-way list structure). Include the algorithm (which you may call balanced()) in a class that also includes a constructor that takes a string of parentheses as a parameter, and a toString() method that returns the expression.
  3. You will, of course, implement this algorithm in two ways, one using MyArrayList and one using MyLinkedList. We'd like to compare the run-time of these two. And we'll do that in two ways as well, both empirically and theoretically. We'll be doing stuff like this in future assignments, so this is a good time to look into it. It's not difficult to time stuff in Java. Maybe you know a better way, but here's one thing you can do. Suppose there's some code you want to time. Then you sandwich it with several lines of code on each end as displayed here:
          Calendar rightNow = Calendar.getInstance();
          int initialTime = rightNow.get(Calendar.MILLISECOND);
          initialTime += rightNow.get(Calendar.SECOND)*1000;
          initialTime += rightNow.get(Calendar.MINUTE)*60*1000;
    
          //Code you want to time
    
          rightNow = Calendar.getInstance();
          int finalTime = rightNow.get(Calendar.MILLISECOND);
          finalTime += rightNow.get(Calendar.SECOND)*1000;
          finalTime += rightNow.get(Calendar.MINUTE)*60*1000;
          System.out.println("Elapsed time = " + (finalTime - initialTime) + " milliseconds");
    
    So... write a driver program and input some large expressions of balanced parentheses to test and compare the run-times of the algorithms based on the two data structures. You should find a significant difference! (Actually, to see that significant a difference, you may need very long expressions. I'll give you one here. Typing this in at the command line may not work, so just hard-code it into the program.)
  4. Explain the difference. What is the run-time of the algorithm (in big-O notation) using ArrayList? What is the run-time of the algorithm using MyLinkedList? Explain your answers.
Back to CS160 Home Page