Java Examples - Searching Linked List

Advertisements


Problem Description:

How to search an element inside a linked list ?

Solution:

Following example demonstrates how to search an element inside a linked list using linkedlistname.indexof(element) to get the first position of the element and linkedlistname.Lastindexof(elementname) to get the last position of the element inside the linked list.

import java.util.LinkedList;

public class Main {
   public static void main(String[] args) {
      LinkedList lList = new LinkedList();
      lList.add("1");
      lList.add("2");
      lList.add("3");
      lList.add("4");
      lList.add("5");
      lList.add("2");
      System.out.println("First index of 2 is:"+
      lList.indexOf("2"));
      System.out.println("Last index of 2 is:"+ 
      lList.lastIndexOf("2"));
   }
}

Result:

The above code sample will produce the following result.

First index of 2 is: 1
Last index of 2 is: 5


Advertisements
Advertisements