Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Recursive method in java

Tags:

java

for homework I was asked to write a contain method for a custom linked list. I know that the recursive method should have a base case and then the recursive case.However, I am having some trouble understanding how to write the recursive case of the method. So far this is what I have written, but my code is executing the base case more than once. Can you please give me some guidance?

public class OrderedList {

private Node first;

//Constructor
public OrderedList() {
    this.first = null;
}

//Return the number of items in the list
public int size() {
    int counter = 0;
    Node pointer = this.first;
    while (pointer != null) {
        counter++;
        pointer = pointer.next;
    }
    return counter;
}

//Return an array of copies of the stored elements
public Comparable[] getStore() {

    Comparable[] elements = new Comparable[size()];
    Node pointer = this.first;
    if (this.first == null) {
        return elements;
    } else {
        int i = 0;
        while (pointer != null) {
            elements[i] = pointer.data;
            pointer = pointer.next;
            i++;
        }
        return elements;
    }

}
//true iff item matches a stored element
//Recursive

public boolean contains(Comparable item) {

    //Base case
    if (this.first == null) {

        return false;
    }
    Node pointer = this.first;
    this.first = this.first.next;

    if (pointer.data.compareTo(item) == 0) {

        return true;

    } 
    //Recursive case

    else {

        boolean info = contains(item);
        pointer.next = this.first;
        this.first = pointer;

        return info;
    }
}
like image 558
jorgeAChacon Avatar asked Oct 22 '22 04:10

jorgeAChacon


1 Answers

First of all I like to do something like this:

public boolean contains(Comparable item)
{
     return containsHelper(this.first, Comparable item);
}

private boolean containsHelper(Node node, Comparable item)
{
    //base case
    if(node == null)
    {   
         return false;
    }
    else
    {
         if(node.data.compareTo(item) == 0)
         {
             return true;
         }

         return containsHelper(node.next, item);
    }


}

This hides implementation details from the user and it stops your list from getting overridden when you run that method.

like image 192
thatidiotguy Avatar answered Oct 24 '22 04:10

thatidiotguy