Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

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

  • Last Updated : 15 Nov, 2021

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:

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

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. 




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!