Skip to content
Related Articles

Related Articles

How to add element at first and last position of linked list in Java?
  • Last Updated : 11 Dec, 2018

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

Examples:

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<String>
            linkedList = new LinkedList<String>();
  
        // Adding elements to the linked list
        // By default elements are inserted at 
        // the last.
        linkedList.add("e");
        linkedList.add("e");
        linkedList.add("k");
        System.out.println("Linked list: "
                           + linkedList);
  
        // Inserting 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.

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.

My Personal Notes arrow_drop_up
Recommended Articles
Page :