Write a Java program to insert the specified element at the specified position in the linked list


This Java code demonstrates how to use a LinkedList to insert an element at a specific position in the list.

  • First, the code imports the java.util.LinkedList class, which is used to create and manipulate linked lists in Java.
  • The Insert_Specified_Position class is defined with a main method, which serves as the entry point for the Java program.
  • Inside the main method, a new LinkedList object named book_list is created with a type parameter of String, which means it will store strings as its elements.
  • Several strings, such as "Java", "C", "Cpp", etc., are added to the book_list using the add method, which appends the elements to the end of the list.
  • The initial contents of the book_list are printed using System.out.println statement, which displays the list as: "Linked list : [Java, C, Cpp, Python, Php, Css, Html, MySql]".
  • Next, the code prints a message stating that a new element will be added after the "Python" element in the list.
  • The add method is called again with two arguments: the index at which the new element should be inserted, which is 4, and the element to be inserted, which is "Bootstrap". This inserts the "Bootstrap" string at the fifth position in the list, shifting the existing elements to the right.
  • Finally, the updated contents of the book_list are printed again using System.out.println statement, which displays the list after inserting the "Bootstrap" element as: "Linked list : [Java, C, Cpp, Python, Bootstrap, Php, Css, Html, MySql]".

Source Code

import java.util.LinkedList;
public class Insert_Specified_Position
{
	public static void main(String[] args)
	{
		LinkedList <String> book_list = new LinkedList <String> ();
		book_list.add("Java");
		book_list.add("C");
		book_list.add("Cpp");
		book_list.add("Python");
		book_list.add("Php");
		book_list.add("Css");
		book_list.add("Html");
		book_list.add("MySql");
		System.out.println("Linked list : "+book_list);
		System.out.println("Let add the Bootstrap color after the Python Color..");
		book_list.add(4, "Bootstrap");
		System.out.println("Linked list :" + book_list);
	}
}

Output

Linked list : [Java, C, Cpp, Python, Php, Css, Html, MySql]
Let add the Bootstrap color after the Python Color..
Linked list :[Java, C, Cpp, Python, Bootstrap, Php, Css, Html, MySql]

Example Programs