4

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

asked Nov 4, 2011 at 1:44

3 Answers 3

2

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;
 }
}
answered Nov 4, 2011 at 2:02
1

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.)

answered Nov 4, 2011 at 1:47
1

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.

answered Nov 4, 2011 at 1:49

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.