How to insert element in LinkedList

In this example we will see how to insert element in Linkedlist at a given index. We can add element in LinkedList at any specific index using LinkedList add(int index,element) method. Let’s see LinkedList.add(int index , elemnt ) method example.

import java.util.LinkedList;

public class AddElement {

public static void main(String[] args) {

LinkedList<String> linkedList = new LinkedList<String>();

linkedList.add("Mumbai");
linkedList.add("Delhi");
linkedList.add("Noida");
linkedList.add("Gao");
linkedList.add("Patna");
//print linkedlist
System.out.println(" Linklist is = "+linkedList);

/*
* Inserts the specified element at the specified position
in this list. Shifts the element currently at that position
(if any) and any subsequent elements to the right
*/

linkedList.add(2, "bangalore");

System.out.println("After Insert Element Linkedlist is = "+linkedList);

}

}

Output:

Linklist is = [Mumbai, Delhi, Noida, Gao, Patna]

After Insert Element Linkedlist is = [Mumbai, Delhi, bangalore, Noida, Gao, Patna]

In this example we have seen how to add element in LinkedList at given index.

A Guide to LinkedList

Leave a Reply

Your email address will not be published. Required fields are marked *

52 − = 51