Tutorial 18-01-2013 Exercises

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 1

06-06994/21699 Software Workshop

Spring Semester 2012-13


Tutorial 18/01/2013

The University of Birmingham


School of Computer Science
Apostolos Giannakidis

Recursion and Lists


Following are some recursion problems that apply on Lists. All methods should
be implemented using recursion without using any local variables.

1. Create a method equal that accepts 2 List objects as arguments and checks
to see if the 2 List objects contain the same elements; i.e. they are equal.
The method should return true if they are equal or false if they contain
different elements. The method signature should be:

public static boolean equal(List a, List b)


Hint: Consider using more than 1 base case.


2. Create a method sumList that accepts a List object as an argument and


calculates and returns the sum of all its elements. The method signature
should be:

public static int sumList(List l)


3. Create an overloaded version of the sumList method that accepts an
integer as a second argument and sums all the elements of the list from
the index denoted by the second argument, until the last element of the
list. The method signature should be:

public static int sumList(List l, int index)


For example, consider a list l with the elements [1,1,3,2]. If we call the
method sumList(l,2), then it should return 5 (3+2=5).

Hint: Consider using more than 1 recursive case.


Notes:
Index 0 should denote the first element.
Index smaller than 0 should be treated as if it was 0.
4. Create a method reverse that accepts a List object as an argument and
returns a new List that is a reverse of the input List object. The method
signature should be:

public static List reverse(List a)


Hint: Consider using a helper method that accepts 2 List objects as


arguments.
Note: Try implementing the method using Tail-Recursion. A tail-
recursive method is one that returns directly the result of the recursive
call; i.e. the recursive call is the last executed operation.

You might also like