John Smith
John Smith

Reputation: 633

Find node from value in linkedlist

I was wondering if there's a way in java to find the position of a node when I have the specific data value as a parameter. For example, if I wanted to remove the node before or after a specific object within the linked list, how would I do this?

Thanks

Upvotes: 4

Views: 8239

Answers (3)

Alexander Pogrebnyak
Alexander Pogrebnyak

Reputation: 45576

Index operations are very inefficient for LinkedList, that's why it's better to use ListIterator. Once you find the item you are looking for, it allows you to move in either direction ( that's the main advantage of the ListIterator over Iterator ).

String search = ...;
LinkedList<String> list = ...;

for(
  ListIterator<String> listIter = list.listIterator( );
  listIter.hasNext();
  listIter.next( )
)
{
  String item = listIter.next( );

  if ( item.equals( search ) )
  {
     if (listIter.hasPrevious())
     {
        listIter.previous( );
        listIter.remove( );
        listIter.next( );
     }

     if (listIter.hasNext())
     {
        listIter.next( );
        listIter.remove( );
     }

     break;
  }
}

Upvotes: 2

Lycha
Lycha

Reputation: 10177

You can call int i = list.indexOf(obj) to get the index of the object. Then just use list.remove(i-1) to remove the previous.

You should add boundary checks so you won't get Exceptions.

Upvotes: 1

Tom
Tom

Reputation: 19304

java.util.List's indexOf( Object o ) method is used to find the index of an object. From there, you should be able to remove an object before it using List's remove(index - 1).

Naturally, this is assuming the linked-list you are using implements the java.util.List interface. (This is definitely true for java's built-in linked list.)

Upvotes: 1

Related Questions