How to Add Elements at a Particular Index in LinkedList

Linked List in Java:

The Linked List is a component of the Collection framework found in the java.util package. This class implements the LinkedList data structure, which is a linear data structure in which the elements are not stored in contiguous locations and each element is a separate object with its own set of properties , a data part and an address part. Pointers and addresses are used to connect the elements. Each element is referred to as a node. They are preferred over arrays due to their dynamic nature and ease of insertions and deletions. It also has a few drawbacks, such as the fact that nodes cannot be accessed directly; instead, we must start at the head and follow the link to the node we want to access.

In this article, we will look at how to add elements to a LinkedList at a specific index or position in Java.

Adding Items at a Particular Index in LinkedList

The element at the end of the LinkedList is always appended by the LinkedList member function add(). Assume we don’t want to add an element at the end of the Linked List, but rather somewhere in the middle.

We’ll use an overloaded version of the add() function to add the element in the middle of the LinkedList.

void addElement(int index, E given_element)

It will insert the specified element into this list at the specified index (position).

Below is the implementation:

import java.io.*;
import java.lang.*;
import java.util.*;
class BtechGeeks {
    public static void main(String[] args)
        throws java.lang.Exception
    {
        // creating a new linked of type string
        List<String> stringlist = new LinkedList<>();

        // adding some elements to the given linkedlist
        stringlist.add("1000");
        stringlist.add("2000");
        stringlist.add("3000");

        // adding some element to 2 nd index in the given
        // linkedlist
        System.out.println(
            "adding element 3874 to 2 nd index");
        stringlist.add(2, "3874");
        // print the linked list
        System.out.println("Linkedlist  = " + stringlist);
        System.out.println(
            "Adding element 6730 to 1 st index");
        // Adding element 6730 to 1 st index
        stringlist.add(1, "6730");
        // print the linked list
        System.out.println("Linkedlist  = " + stringlist);
    }
}

Output:

adding element 2811 to 2 nd index
Linkedlist = [1000, 2000, 3874, 3000]
Adding element 6730 to 1 st index
Linkedlist = [1000, 6730, 2000, 3874, 3000]

Related Programs: