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


This Java code demonstrates how to use the offerLast() method to insert an element at the end of a linked list.

  • The code defines a class named InsertElement_End with a main method, which serves as the entry point for the Java program.
  • Inside the main method, a new LinkedList object named col_list is created with a type parameter of String, indicating that it will store strings as its elements.
  • Strings such as "Blue", "White", "Red", etc., are added to the col_list using the add method, which appends the elements to the end of the list.
  • The System.out.println statement is used to print the initial contents of the col_list before any modifications.
  • The offerLast() method is called on the col_list to insert the element "Orange" at the end of the linked list. This is done using the offerLast() method, which is a specialized method for adding an element to the end of the linked list.
  • The System.out.println statement is used to print the contents of the col_list after inserting the element "Orange" at the end of the list, using the offerLast() method.
  • The output of the program will be the initial contents of the col_list printed on the first line, followed by the contents of the list after inserting "Orange" at the end, printed on the subsequent line.

Source Code

import java.util.LinkedList;
public class InsertElement_End
{
	public static void main(String[] args)
	{
		LinkedList<String> col_list = new LinkedList<String>();
		col_list.add("Blue");
		col_list.add("White");
		col_list.add("Red");
		col_list.add("Pink");
		col_list.add("Green");
		col_list.add("Black");
		System.out.println("Given Linked list :" + col_list);
		col_list.offerLast("Orange");
		System.out.println("Linked list :" + col_list);  
	}
}

Output

Given Linked list :[Blue, White, Red, Pink, Green, Black]
Linked list :[Blue, White, Red, Pink, Green, Black, Orange]

Example Programs