Snowman
Snowman

Reputation: 32081

Recursion and LinkedList in Java

Ok so say I have a function that looks for a specific word in a custom LinkedList class:

public LinkedList find(String word) {
    if (this.word.equals(word))
        return this;
    if (next==null)
        return null;
    if (next.find(word)==next)
        return next;
    return null;
}

This code works fine, however it returns the FIRST found object that matches the criteria. What if I wanted to return the LAST object found that matches the paramater? I'm having a hard time figuring this out. Keep in mind I want to use recursion.

EDIT: What would be wrong with this code:

public LinkedList findLast(String word) {
    LinkedList temp=new LinkedList(word, null);
    if (next==null && next.word.equals(word))
        return next;
    if (next==null && !next.word.equals(word))
        temp=next.findLast(word);
    return temp;
}

Upvotes: 1

Views: 2699

Answers (7)

Peter Knego
Peter Knego

Reputation: 80340

public LinkedList find(String word, LinkedList result) {
   if (this.word.equals(word))
        result = this;
   if (next != null )
        return next.find(word, result)
   return result;

Two-liner:

public LinkedList find(String word, LinkedList result) {
     result = this.word.equals(word) ? this : result;
     return next == null ? result : next.find(word, result);

@fprime: Ya, explanation: remember the result, replace it with later result, return when at the end.

Method with one argument:

public LinkedList find(String word){
   result = this.word.equals(word) ? this : null;
   if(next != null)
      previous = next.find(word);
      return (previous != null) ? previous : result 
   else 
      return result;

Upvotes: 1

khachik
khachik

Reputation: 28703

public LinkedList find(String word) {
  if(this.word.equals(word)) return this;
  return next==null?null:next.find(word);
}

public LinkedList rfind(String word) { if(next != null) { LinkedList res = next.rfind(word); if(res != null) return res; } return this.word.equals(word)?this:null; }

Upvotes: 0

Bane
Bane

Reputation: 1782

Store a reference to the latest one found and keep on calling itself until it returns null -- then return the latest-reference.

Note, for clarification: you're going to have to iterate through your entire linked-list (unless you have a doubly-linked-list) to achieve this -- store a reference every time you find a match (but just overwrite the same reference each time) -- then return whatever the reference holds once you reach the end of this list.

public class LinkedList {

  private static int uniqueIdCounter = 0;

  private final String word;
  private int uniqueId;
  private LinkedList next = null;

  public LinkedList( String word ) {

    this.word = word;
    this.uniqueId = uniqueIdCounter++;
  }

  @Override
  public String toString() {

    return this.word + "(" + this.uniqueId + ")";
  }



  public void setNext( LinkedList next ) {

    this.next = next;
  }

  public LinkedList find( String word ) {

    return this.find( word, null );
  }

  public LinkedList find( String word, LinkedList result ) {

    if( this.word.equals( word ) ) {
        result = this;
    }

    if( this.next != null ) {

        result = this.next.find(word, result);
    }

    return result;
  }

  public static void main(String[] args) {

    LinkedList head = new LinkedList( "A");
    System.out.println( "Head is: " + head );

    LinkedList B = new LinkedList( "B" );
    head.setNext( B );
    System.out.println( "B is: " + B );

    LinkedList A2 = new LinkedList( "A" );
    B.setNext( A2 );
    System.out.println( "A2 is: " + A2 );

    LinkedList last = head.find( "A" );
    System.out.println( "Last is: " + last );
  }

}

And here's the output:

Head is: A(0)

B is: B(1)

A2 is: A(2)

Last is: A(2)

Upvotes: 3

ILMTitan
ILMTitan

Reputation: 11037

To start with, you initial find(String word) does not work correctly.

Your first if statement is perfect. It is you success base case.

Your second if statement is also perfect. It is your failure base case.

Your third is where you go off the rails. You have handled all (in this case both) base cases, now all that is left is the recursive case. You don't need to check anything here. next.find(word) will return the correct answer, success or fail.

For findLast(String word), I can't add much to what Jon Skeet said. About the only advice I can add it to never have the a node check its neighbor. Each node should only ever check itself. You should see plenty of this.word.equals(word) but never next.word.equals(word).

Upvotes: 0

Kel
Kel

Reputation: 7790

Every straight recursive function has two places for some useful actions: before further method call and after:

  function(n){
    doBefore(n);
    function(n+1)
    doAfter(n)
  }

doBefore() is executed "on the way forward", doAfter() is executed "on the way back". Now your algorithm checks word equality on the way forward. You have to modify your algorithm so that this check is performed on the way back.

Upvotes: 2

bhavinp
bhavinp

Reputation: 833

Just run it backwards from the tail.

public LinkedList find(String word) {
        if (this.word.equals(word))
            return this;
        if (prev==null)
            return null;
        if (prev.find(word)==prev)
            return prev;
        return null;
}

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1504182

Well, think of it this way: you need to recurse right to the end of the list, and then let the return value bubble up.

So the start of your method should either be a recursive call to look further down the list, or noting that we're at the end of the list - which is equivalent to the "further" result being null.

Now when you're returning, there are three options:

  • You've already found a match later than the current point - so return that reference
  • You've not found a match (so the return value of the recursive call was null) and:
    • The current point's word matches - so return the current point
    • The current point doesn't match - so return null

Hopefully that should be enough to get you to an implementation - if not, please ask more questions. I'd rather not give a full implementation when this is presumably homework.

Upvotes: 8

Related Questions