Remove First and Last Elements from LinkedList in Java
Last Updated :
06 Apr, 2023
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
import java.util.LinkedList;
class GFG {
public static void main (String[] args) {
LinkedList<String> list = new LinkedList<String>();
list.add( "Geek" );
list.add( "for" );
list.add( "Geeks" );
list.add( "2020" );
list.add( "2021" );
System.out.println( "LinkedList:\t" + list);
System.out.println( "The last element is removed:\t" + list.removeLast());
System.out.println( "Final LinkedList:\t" + list);
System.out.println( "The first element is removed:\t" + list.removeFirst());
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]
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...