Search code examples
javastringlistfindtraversal

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.


Solution

  • 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
    }