Write a Java program to insert elements into the linked list at the first and last position
This Java code demonstrates how to use a LinkedList to add elements at the beginning and end of the list using the addFirst and addLast methods.
- First, the code imports the java.util.LinkedList class, which is used to create and manipulate linked lists in Java.
- The InsertElement_FirstLast 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", "Cpp", "Php", 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 : [Java, Cpp, Php, Css, Html, MySql]".
- The addFirst method is called on book_list with the argument "C", which adds the string "C" as the first element in the list, shifting the existing elements to the right.
- The addLast method is called on book_list with the argument "Python", which adds the string "Python" as the last element in the list, appending it to the end of the list.
- Finally, the updated contents of the book_list are printed again using a System.out.println statement, which displays the list after adding the elements "C" and "Python" as: "Final linked list : [C, Java, Cpp, Php, Css, Html, MySql, Python]".
Source Code
import java.util.LinkedList;
public class InsertElement_FirstLast
{
public static void main(String[] args)
{
LinkedList<String> book_list = new LinkedList<String>();
book_list.add("Java");
book_list.add("Cpp");
book_list.add("Php");
book_list.add("Css");
book_list.add("Html");
book_list.add("MySql");
System.out.println("Given linked list : " + book_list);
book_list.addFirst("C");
book_list.addLast("Python");
System.out.println("Final linked list : " + book_list);
}
}
Output
Given linked list : [Java, Cpp, Php, Css, Html, MySql]
Final linked list : [C, Java, Cpp, Php, Css, Html, MySql, Python]