How to add element at first and last position of linked list in Java?

Given a Linked List in Java, the task is to insert elements at first and last position in this LinkedList.


Input: LinkedList: [‘e’, ‘e’, ‘k’], insert at first = ‘G’, insert at last = ‘s’
Output: LinkedList: [‘G’, ‘e’, ‘e’, ‘k’, ‘s’]

Input: LinkedList: [2, 3, 4], insert at first = 1, insert at last = 5
Output: LinkedList: [1, 2, 3, 4, 5]

This can be achieved with the help of LinkedList.addFirst() and LinkedList.addLast() methods of LinkedList class in Java.

Below is the implementation of the above approach:





// Java program to insert elements
// at first and last position in the LinkedList
import java.util.*;
public class GFG {
    public static void main(String args[])
        // Creating linked list
            linkedList = new LinkedList<String>();
        // Adding elements to the linked list
        // By default elements are inserted at 
        // the last.
        System.out.println("Linked list: "
                           + linkedList);
        // Inserting at first position
        // Inserting at last position
        // Print the updated LinkedList
        System.out.println("Updated Linked list: "
                           + linkedList);



Linked list: [e, e, k]
Updated Linked list: [G, e, e, k, s]

Note : add() and addLast() provide same functionality. LinkedList implements two interfaces, Deque and Queue. It inherits add() from Deque and addLast() from Queue.

Attention reader! Don’t stop learning now. Get hold of all the important Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.