Traversing though list, if object string is not on the list then return null

Let's say I have 7 muppets on my list. They all have names (strings). The program returns the muppet (object) if their name is on the list. Now the problem is that how do I return null if none of the 7 muppets on my list match the parameter name? I know how to return null with the head node by simply returning null if the head node name is equal to null. But how do I do that with the rest of the list?

public Muppet peek(String name) {
    if(start == null) { // if the start Muppet is equal to null, so there's nothing on the list
        return null;
    if(start.getName().equals(name)) {   // return the muppet at the start of the list
        return start;
    } else  {
        Muppet previous = start;
        while(!previous.getNext().getName().equalsIgnoreCase(name)) { // traverse through the whole list
            previous = previous.getNext();
        Muppet current = previous.getNext();
        return current; // Return the muppet that was asked

Read more here:

Content Attribution

This content was originally published by Coder248 at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: