

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!


Spring 2008 Recursion (S&W Chapter 6) This is a self-help exercise. You should do the exercises, but they need not be handed in. Answers are available for you to check your work. In these exercises, you will write recursive algorithms in an English, or Java-like pseudo code. In problems 1-6 assume that L is a list (abstract data type) of integers and that the following methods are available in the List class. head () returns the value of the first element of L. head is undefined if L is empty. tail () returns a list that is everything in L except the head. tail() is undefined if L is empty. isEmpty () returns true if L is empty; false if L is not empty. The List class has the following constructors. List() Creates a new empty list. List(List L) Creates a new list that is a copy of L. Also assume that we have the utility method concat that returns a list that is the concatenation of the lists given as parameters. For example, concat (L 1 , L 2 , L 3 ) returns a list that is the concatenation of the three lists. Since these are all in pseudo code, we can further assume that concat can also take integers as parameters. So for example concat (L 1 , 5, L 2 ) returns a list containing all the elements in list L 1 followed by a 5 followed by all the elements in L 2. Example Define a recursive algorithm that determines whether L has at least one entry greater than or equal to 100. public boolean containsGTE100(List L) { // pre true // post returns true iff L contains a value >= if (L.isEmpty()) return false; // Easy case: empty list // doesn’t contain element >= else if (L.head()>=100) return true; // Head of list >= 100 else return containsGTE100(L.tail()); // Look for 100+ further down } Write recursive methods that do the following.