Search

Sunday, July 19, 2015

How to search an element inside LinkedList in Java? Example

You can search an element inside LinkedList in Java by using indexOf() and lastIndexOf() methods. Though LinkedList doesn't support random search like ArrayList, you can still go through the list, check each element and find out whether its interested element or not. Since java.util.LinkedList is an implementation of doubly linked list, these two methods are quite handy to search from either ends e.g. indexOf() method start search from head and return an elements position, while lastIndexOf() starts search from tail. Though, position is not relative to ends, they are always calculated from head. You can also use these two methods to find out duplicate elements. If an element is appeared twice in linked list then indexOf() and lastIndexOf() method will return different positions for that because it will be found at different position from head and tail. For unique elements, both these methods will return same position. In this article, you will see examples of both indexOf() and lastIndexOf() methods to search a given element inside LinkedList. As I said before, since LinkedList doesn't support random search and searching an element require list traversal, which means time complexity will be O(n). BTW, if you are good in Java but lacks data structure and algorithm skill, I strongly suggest to read Data Structures and Algorithm Analysis in Java by Mark A. Wiess. It's a great book to build your foundation on data structure and algorithm using Java programming language.
Read more »

No comments:

Post a Comment