LinkedList pop() Method in Java
In Java, the pop() method of the LinkedList class is used to remove and return the top element from the stack represented by the LinkedList. The method simply pops out an element present at the top of the stack. This method is similar to the removeFirst method in LinkedList.
Example 1: Here, we use the pop() method to remove and return the first element (head) of the LinkedList.
// Java Program to Demonstrate the
// use of pop() in LinkedList
import java.util.LinkedList;
class Geeks {
public static void main(String[] args) {
// Creating an empty LinkedList
LinkedList<Integer> l = new LinkedList<>();
// use add() to add
// elements in the list
l.add(100);
l.add(200);
l.add(300);
l.add(400);
System.out.println("" + l.pop());
System.out.println("" + l);
}
}
Output
100 [200, 300, 400]
Syntax of LinkedList pop() Method
public E pop()
- Return Type: This method returns the element that is removed from the head of the list.
- Exception: If the list is empty, calling pop() will throw a NoSuchElementException.
Example 2: Here, the pop() is going to throw an NoSuchElementException
if the list is empty.
// Handling an empty LinkedList with pop()
import java.util.LinkedList;
class Geeks {
public static void main(String[] args) {
// Here we are trying to pop
// an element from an empty list
try {
LinkedList<String> l = new LinkedList<>();
l.pop();
}
catch (Exception e) {
System.out.println("Exception caught: " + e);
}
}
}
Output
Exception caught: java.util.NoSuchElementException