Friday, September 5, 2025
HomeLanguagesJavaHow to Add Element at First and Last Position of LinkedList in...

How to Add Element at First and Last Position of LinkedList in Java?

LinkedList is a part of Collection framework present inside java.util package. This class is an implementation of LinkedList data structure which is a linear data structure where the elements are not stored in a contiguous manner and every element is a separate object with a data field and address field. Now here we are given a Linked List, the task is pretty simple that is to insert elements at the first and last position in this LinkedList which is carried out with help of methods present inside the LinkedList class that is addFirst() and addLast() method.

Illustration:

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] 

As we mentioned above it can be achieved when aided with the help of addFirst() and addLast() methods of the LinkedList class.

Example:

Java




// Java program to Insert Elements in LinkedList
// at first and last position to showcase
// addFirst() and addlast() Method
  
// Importing required classes
import java.util.*;
  
// Main class
public class GFG {
  
    // Main driver method
    public static void main(String args[])
    {
        // Creating an empty LinkedList of string type
        LinkedList<String> linkedList
            = new LinkedList<String>();
  
        // Note: By default, elements are inserted at last
  
        // Adding elements to the linkedList
        // using add() method
        linkedList.add("e");
        linkedList.add("e");
        linkedList.add("k");
  
        // Printing the elements in current LinkedList
        System.out.println("Linked list: " + linkedList);
  
        // Customly inserting element at first position
        linkedList.addFirst("G");
  
        // Inserting at last position
        linkedList.addLast("s");
  
        // Print the updated LinkedList
        System.out.println("Updated Linked list: "
                           + linkedList);
    }
}


Output: 

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. 

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32267 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6635 POSTS0 COMMENTS
Nicole Veronica
11801 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11865 POSTS0 COMMENTS
Shaida Kate Naidoo
6752 POSTS0 COMMENTS
Ted Musemwa
7026 POSTS0 COMMENTS
Thapelo Manthata
6703 POSTS0 COMMENTS
Umr Jansen
6720 POSTS0 COMMENTS