This is a brief outline of the lecture.
Defn: A method m(...) is said to be recursive if m(...) calls itself (i.e., the same method, with the same number and type of parameters). The recursive call could be made directly within m(...) or indirectly through several other method calls.
We wish to practice writing recursive methods.
Prerequisite: Understand the runtime stack.
To write a recursive method for some task, ask yourself three questions:
Example 1 On the board in class we designed, wrote, traced, and debugged a recursive method to remove the first occurrence of an object o from a stack s, leaving the other items in the stack in FIFO order.
Solution. Answers to 3 questions:
/** Remove the first occurrence of o from the stack s.
* @param s the stack, must not be null.
* @param o the item to be removed, must not be null.
* @return true if the item was found and removed, else false. */
public static boolean deleteFirst(Stack s, Object o) {
if (s.size() == 0)
return false;
Object current = s.pop();
if (o.equals(current))
return true; // toss current
boolean result = deleteFirst(s, o);
s.push(current);
return result;
}
Key Point In writing this code it is easiest if you trust your friend to do their job. Don't think about how your friend does their job (this often gets messy). Just make sure you do your job.
Example 2 Given a non-null Queue q, reverse it.
Solution. Answers to 3 questions: