Find node from value in linked list

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

thanks

+4
source share
3 answers

Index operations are very inefficient for LinkedList , so it is better to use ListIterator . When you find the item you are looking for, it allows you to move in any direction (which is the main advantage of 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; } } 
+2
source

java.util.List indexOf( Object o ) uses the object index search method. From there, you must remove the object before using it List remove(index - 1) .

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

+1
source

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

You must add border checks so that you do not receive Exceptions.

+1
source

Source: https://habr.com/ru/post/1379576/


All Articles