Write a Java program to insert the specified element at the front of a linked list


This Java code demonstrates how to insert an element at the front of a linked list using the java.util.LinkedList class.

  • The code defines a class named InsertElement_Front 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, indicating that it will store strings as its elements.
  • Strings such as "Cpp", "Php", "Css", 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 a System.out.println statement, which displays the list as: "Given linked list : [Cpp, Php, Css, Python, MySql]".
  • The offerFirst method is called on the book_list to insert the string "Java" at the front of the list. This method is used to add an element to the beginning of the list, similar to the addFirst method.
  • The updated contents of the book_list are printed again using a System.out.println statement, which displays the list as: "Final linked list : [Java, Cpp, Php, Css, Python, MySql]".
  • Note that the "Java" element is now added at the front of the list, pushing the existing elements to the right.
  • The code does not perform any further operations or modifications to the linked list, so the program will simply print the initial and updated contents of the list and then terminate.
  • The output of the program will be the initial and updated contents of the book_list linked list, which is: "Given linked list : [Cpp, Php, Css, Python, MySql]" and "Final linked list : [Java, Cpp, Php, Css, Python, MySql]".

Source Code

import java.util.LinkedList;
public class InsertElement_Front
{
	public static void main(String[] args)
	{
		LinkedList<String> book_list = new LinkedList<String>();
		book_list.add("Cpp");
		book_list.add("Php");
		book_list.add("Css");
		book_list.add("Python");
		book_list.add("MySql");
		System.out.println("Given linked list : "+ book_list);
		book_list.offerFirst("Java");
		System.out.println("Final linked list : "+ book_list);  
	}	
}

Output

Given linked list : [Cpp, Php, Css, Python, MySql]
Final linked list : [Java, Cpp, Php, Css, Python, MySql]

Example Programs