Saturday, September 6, 2025
HomeLanguagesJavaRemove First and Last Elements from LinkedList in Java

Remove First and Last Elements from LinkedList in Java

The Java.util.LinkedList.removeFirst() method is used to remove the first element from the LinkedList. 

The Java.util.LinkedList.removeLast() method is used to remove the last element from the LinkedList. Both the methods also returns the element after removing it.

1.  removeFirst() 

Syntax:  

LinkedList.removeFirst()

Parameters: This function does not take any parameters.

Return Value: The method returns the first element or the element present at the head of the list.

2.  removeLast()

Syntax:  

LinkedList.removeLast()

Parameters: This function does not take any parameters.

Return Value: The method returns the last element or the element present at the tail of the list.

Example:

Java




// Java program to illustrate the Java.util.LinkedList.remove() method
// and Java.util.LinkedList.removeLast() method
 
import java.util.LinkedList;
 
class GFG {
    public static void main (String[] args) {
       
        // Creating an LinkedList
        LinkedList<String> list = new LinkedList<String>();
 
        // Use add() method to add elements in the list
        list.add("Geek");
        list.add("for");
        list.add("Geeks");
        list.add("2020");
        list.add("2021");
 
        // Displaying the list
        System.out.println("LinkedList:\t" + list);
 
        // Remove the tail using removeLast()
        System.out.println("The last element is removed:\t" + list.removeLast());
         
        // Displaying the final list
        System.out.println("Final LinkedList:\t" + list);
         
        // Remove the head using remove()
        System.out.println("The first element is removed:\t" + list.removeFirst());
 
        // Displaying the final list
        System.out.println("Final LinkedList:\t" + list);
    }
}


Output

LinkedList:    [Geek, for, Geeks, 2020, 2021]
The last element is removed:    2021
Final LinkedList:    [Geek, for, Geeks, 2020]
The first element is removed:    Geek
Final LinkedList:    [for, Geeks, 2020]
RELATED ARTICLES

Most Popular

Dominic
32270 POSTS0 COMMENTS
Milvus
82 POSTS0 COMMENTS
Nango Kala
6639 POSTS0 COMMENTS
Nicole Veronica
11803 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11869 POSTS0 COMMENTS
Shaida Kate Naidoo
6752 POSTS0 COMMENTS
Ted Musemwa
7029 POSTS0 COMMENTS
Thapelo Manthata
6704 POSTS0 COMMENTS
Umr Jansen
6721 POSTS0 COMMENTS