LinkedList pop() Method in Java
Last Updated :
12 Jan, 2023
The java.util.LinkedList.pop() method 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 removeFirst method in LinkedList. Syntax:
LinkedListObject.pop()
Parameters: The method does not take any parameter. Return Value: The method returns the first(top in terms of a stack) value of the stack represented by the LinkedList. Exception: If there is no element in the stack represented by the LinkedList, the pop method will throw NoSuchElementException(). Below program illustrates the of java.util.LinkedList.pop() method: Program 1:
java
import java.util.LinkedList;
public class GfG {
public static void main(String[] args)
{
LinkedList<String> stack = new LinkedList<>();
stack.push("Geeks");
stack.push(" for ");
String s = stack.pop();
System.out.println(s);
stack.push("Geeks");
System.out.println(stack);
}
}
|
Output:
for
[Geeks, Geeks]
Program 2 :
Java
import java.util.LinkedList;
public class GfG {
public static void main(String[] args)
{
LinkedList<Integer> stack = new LinkedList<>();
stack.push( 10 );
stack.push( 20 );
Integer ele = stack.pop();
System.out.println(ele);
ele = stack.pop();
System.out.println(ele);
ele = stack.pop();
System.out.println(ele);
System.out.println(stack);
}
}
|
Output:
20
10
then it will throw :
Exception in thread "main" java.util.NoSuchElementException
at java.util.LinkedList.removeFirst(LinkedList.java:270)
at java.util.LinkedList.pop(LinkedList.java:801)
at GfG.main(GfG.java:35)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...