Open In App
Related Articles

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

Like Article
Save Article
Report issue

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.


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.



// 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
        // Printing the elements in current LinkedList
        System.out.println("Linked list: " + linkedList);
        // Customly inserting element 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. 

Last Updated : 15 Nov, 2021
Like Article
Save Article
Share your thoughts in the comments
Similar Reads