LinkedList removeFirst() Method in Java
In Java, the LinkedList class provides the removeFirst() method to remove and return the first element of the list. If the list is empty, the method throws a NoSuchElementException.
Sure, here is an example of using the removeFirst() method in Java, with the full code and output:
Java
import java.util.LinkedList;
public class Example {
public static void main(String[] args) {
LinkedList<String> list = new LinkedList<>();
list.add( "apple" );
list.add( "banana" );
list.add( "orange" );
list.add( "grape" );
System.out.println( "Original list:" );
System.out.println(list);
String removed = list.removeFirst();
System.out.println( "Element removed: " + removed);
System.out.println(list);
}
}
|
Output
Original list:
[apple, banana, orange, grape]
Element removed: apple
[banana, orange, grape]
In this example, we first create a LinkedList object and add four elements to it. The System.out.println() statement prints the original list to the console.
We then use the removeFirst() method to remove the first element from the list (which is “apple”), and print the removed element and the updated list to the console.
The Java.util.LinkedList.removeFirst() method is used to remove the first element from a linked list. This function also returns the first element after removing it. 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.
Below program illustrates the Java.util.LinkedList.removeFirst() method:
Java
import java.io.*;
import java.util.LinkedList;
public class LinkedListDemo {
public static void main(String args[])
{
LinkedList<String> list = new LinkedList<String>();
list.add( "Geeks" );
list.add( "for" );
list.add( "Geeks" );
list.add( "10" );
list.add( "20" );
System.out.println( "LinkedList:" + list);
System.out.println( "The first element is: "
+ list.removeFirst());
System.out.println( "Final LinkedList:" + list);
}
}
|
Output
LinkedList:[Geeks, for, Geeks, 10, 20]
The first element is: Geeks
Final LinkedList:[for, Geeks, 10, 20]
Example:
Java
import java.io.*;
import java.util.LinkedList;
public class LinkedListDemo {
public static void main(String args[])
{
LinkedList<String> list = new LinkedList<String>();
list.add( "Geeks" );
list.add( "for" );
list.add( "Geeks" );
list.add( "10" );
list.add( "20" );
System.out.println( "LinkedList:" + list);
System.out.println( "The first element is: "
+ list.removeFirst());
System.out.println( "Final LinkedList:" + list);
}
}
|
Output
LinkedList:[Geeks, for, Geeks, 10, 20]
The first element is: Geeks
Final LinkedList:[for, Geeks, 10, 20]
Last Updated :
31 Mar, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...