Find position of element in linked list Java

How to find the index of an element in the LinkedList in Java?

Use the indexOf method of the LinkedList class to find the index of the first occurrence of an element in the list.

1
public int indexOf[Object o]

The indexOf method returns the index of the first occurrence of the specified element object in the list. If the specified element is not found in the list. it returns -1.

Similarly, use the lastIndexOf method of the LinkedList class to find the last occurrence of the specified element in the list.

1
public int lastIndexOf[Object o]

This method also returns -1 if the element is not found in the list, otherwise, it returns the index of the last occurrence of the specified element in the list.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import java.util.LinkedList;
public class FindElementIndexInLinkedListExample {
public static void main[String[] args] {
//create new LinkedList object
LinkedList linkedListNumbers = new LinkedList[];
//add elements
linkedListNumbers.add[1];
linkedListNumbers.add[2];
linkedListNumbers.add[3];
linkedListNumbers.add[1];
linkedListNumbers.add[2];
linkedListNumbers.add[3];
/*
* To find first occurrence of an element in LinkedList, use
* the indexOf method
*/
int index = linkedListNumbers.indexOf[3];
if[index == - 1]{
System.out.println["Element not found"];
}else{
System.out.println["Element found at index " + index];
}
/*
* To find last occurrence of an element, use the
* lastIndexOf method
*/
index = linkedListNumbers.lastIndexOf[3];
if[index == - 1]{
System.out.println["Element not found"];
}else{
System.out.println["Last occurrence of an element found at index " + index];
}
//this will return -1 as the linked list does not contain 4
System.out.println[ linkedListNumbers.indexOf[4] ];
}
}

Output

1
2
3
Element found at index 2
Last occurrence of an element found at index 5
-1

Java.util.LinkedList.indexOf[] Method

Advertisements

Previous Page
Next Page

Java Program to search element inside linked list

Here is our sample program to search a given node inside LinkedList in Java. We first build our linked list of numbers and insert 1003 twice to make it a duplicate number. Later we have used theindexOf[] and lastIndexOf[] method to search for a duplicate element like 1003 and a unique element 1002 inside the linked list.

From the result, you can see that indexOf[] starts the search from the first element and that's why it found 1003 at the 3rd position, which is index 2. On the other hand, lastIndexOf[] starts the search from the last element and that's why it found 1003 at 6th position i.e. index 5.

Here is a sample doubly linked list data structure :



and here is our example to search duplicate and unique nodes inside LinkedList in Java.

import java.util.LinkedList; /** * Java Program to search an element inside LinkedList. * LinkedList doesn't provide random search and * time complexity of searching is O[n] * * @author java67 */ public class LinkedListSearch { public static void main[String args[]] { LinkedList ints = new LinkedList[]; ints.add[1001]; ints.add[1002]; ints.add[1003]; ints.add[1004]; ints.add[1005]; ints.add[1003]; // let's search a duplicate element in linked list // for duplicate elements indexOf[] and lastIndexOf[] will // return different indexes. System.out.println["First index of 1003 is : " + ints.indexOf[1003]]; System.out.println["Last index of 1003 is : " + ints.lastIndexOf[1003]]; // let's search an element which is not appeared twice // for unique elements both indexOf[] and lastIndexOf[] will return // same position System.out.println["First index of 1002 is : " + ints.indexOf[1002]]; System.out.println["Last index of 1002 is : " + ints.lastIndexOf[1002]]; } } Output : First index of 1003 is : 2 Last index of 1003 is : 5 First index of 1002 is : 1 Last index of 1002 is : 1
From the output, you can also see those duplicate nodes has two different positions returned by indexOf[] and lastIndexOf[] method while for unique elements both methods return the same index.

Btw, If you are good in Java but lacks data structure and algorithm skills, I strongly suggest readingData Structures and Algorithm Analysis in Javaby Mark A. Wiess. It's a great book to build your foundation on data structure and algorithms using Java programming language.


That's all about how to search an element inside LinkedList in Java. Searching an element requires traversing the list from either end, for example from head to tail or tail to head, which is what indexOf[] and lastIndexOf[] method does. You can use any of these methods to find out the index of a given element in Java, but just remember that if the element is repeated then both methods can return different indices.


If you like this tutorial and interested to learn more about linked list data structure in Java, You can also check the following Java LinkedList tutorials :
  • How to add elements at the first and last position in LinkedList in Java? [example]
  • The difference between LinkedList and ArrayList in Java? [answer]
  • Top 5 data structures from Java Collections framework? [article]
  • How to implement a linked list in Java? [solution]
  • How to find the middle node of the linked list in one pass? [solution]
  • How do you find the length of a singly linked list in Java? [solution]
  • What is the difference between a linked list and an array in Java? [answer]
  • How to find the first and last element from LinkedList in Java? [example]
  • How to check if the linked list contains a loop in Java? [solution]

What is the LinkedList.get[int index] method in Java?

A linked list is a collection of linear data elements. Each element [node] contains data and reference parts. The data part has the value and the reference part has the address link to the next element.

The elements are not indexed, so random access like an array is not possible. Instead, we traverse from the beginning of the list and access the elements.

In Java, the LinkedList class is thedoubly-linked listA kind of linked list. Each node contains three fields: two link fields [one for the previous element and another for the next element] and one data field.implementation of the List and Deque interfaces. The LinkedList class is present in the java.util package.

The get method

The get method can be used to get the element at the specified index of the LinkedList.

Syntax

public E get[int index];

Parameters

This method takes the index of the element to be retrieved as an argument.

Return value

This method returns the element at the specified index of the list.

The IndexOutOfBoundsException exception is thrown if the index is negative or greater than the list size [index < 0 || index >= size[]].

Code

The code below demonstrates how to use the get method.

import java.util.LinkedList; class LinkedListGetExample { public static void main[ String args[] ] { LinkedList list = new LinkedList[]; list.add["1"]; list.add["2"]; list.add["3"]; System.out.println["The list is " + list]; System.out.println["The element at index 0 is " + list.get[0]]; System.out.println["The element at index 1 is " + list.get[1]]; System.out.println["The element at index 2 is " + list.get[2]]; } }
Run

Explanation

In the code above:

  • In line 1, we imported the LinkedList class.
import java.util.LinkedList;
  • In line 4, we created a LinkedList object with the name list.
LinkedList list = new LinkedList[];
  • From lines 5 to 7, we used the add method of the list object to add three elements ["1","2","3"] to the list.
list.add["1"]; list.add["2"]; list.add["3"];
  • In line 10, we used the get method of the list object to get the element at index 0.
list.get[0]; // "1"
  • In line 11, we used the get method of the list object to get the element at index 1.
list.get[1]; // "2"
  • In line 12, we used the get method of the list object to get the element at index 2.
list.get[2]; // "3"

Video liên quan

Bài mới nhất

Chủ Đề