Write a Java program to Insert an element at the head and tail of a LinkedList


The code demonstrates how to add elements to the head and tail of a LinkedList in Java. The InsertElement_HeadTail class contains a main method where a LinkedList of strings, list, is created and initially populated with some values using various methods such as add, addLast, offer, and offerLast.

The add and addLast methods are used to add elements at the end of the linked list, while the offer and offerLast methods are used to do the same, but with different return behaviors. The System.out.println statements are used to print the initial state of the linked list after adding elements at the end of the list.

Then, additional elements are added at the beginning of the list using the add, addFirst, offer, and offerFirst methods. These methods add elements at the head of the linked list. Finally, the resulting linked list after adding elements at the beginning of the list is printed using System.out.println.

Source Code

import java.util.*;
public class InsertElement_HeadTail
{
    public static void main(String[] args)
    {
        LinkedList<String> list = new LinkedList<String>(); 
 
        //Adding elements at the end of the list 
        list.add("Red"); 
        list.addLast("Green"); 
        list.offer("Pink"); 
        list.offerLast("Orange"); 
        System.out.println("Adding elements at the end of the list..");
        System.out.println(list);
 
        //Adding elements at the beginning of the list 
        list.add("Yellow"); 
        list.offerFirst("Blue"); 
        list.addFirst("White"); 
        list.offer("Black"); 
        System.out.println("Adding elements at the beginning of the list..");
        System.out.println(list);
    }
}

Output

Adding elements at the end of the list..
[Red, Green, Pink, Orange]
Adding elements at the beginning of the list..
[White, Blue, Red, Green, Pink, Orange, Yellow, Black]

Example Programs