user3450277
user3450277

Reputation: 436

Traversing through a LinkedList in an odd way?

I want to be able to find the data immediately before an given piece of data. For example, say you had a list of names:

Bob, Tommy, Scott, Frank, Evan, Ryan, Jessy, Alex, Abner, Edward, Smith, Adam

A hypothetical method find() is passed a name, and returns the name immediately before it, sequentially.

For example, you run find(Ryan), which has a desired result of returning Evan. How would you accomplish this? Since there is no iterator, I am unsure how this would be done.

Upvotes: 0

Views: 41

Answers (2)

sprinter
sprinter

Reputation: 27946

One option is to use indexOf:

public String find(List<String> names, String name) {
    int index = names.indexOf(name);
    return index > 0 ? names.get(index - 1) : null;
}

However this is pretty inefficient as both indexOf and get require iteration. For relatively small lists this is unlikely to be an issue.

Upvotes: 3

Jean-Fran&#231;ois Savard
Jean-Fran&#231;ois Savard

Reputation: 21004

Here a simple snippet that would fix your issue

LinkedList<String> yourListWithName = new LinkedList<String>();
//Fill your list

ListIterator<String> listIterator = yourListWithName.listIterator();

String previous = null;

while(listIterator.hasNext()) {

    if(listIterator.hasPrevious())
    {

        previous = listIterator.previous();
        listIterator.next();
    }

    String current = listIterator.next();

    if(current.equals(yourReceivedName))
        //Your algorithm
}

Upvotes: 4

Related Questions