java.util.LinkedList.pop()方法用于从LinkedList表示的堆栈中删除并返回顶部元素。该方法只是弹出出现在堆栈顶部的元素。此方法类似于LinkedList中的removeFirst方法。
用法:
LinkedListObject.pop()
参数:该方法不带任何参数。
返回值:该方法返回由LinkedList表示的堆栈的first(栈顶)值。
异常:如果LinkedList表示的堆栈中没有元素,则pop方法将引发NoSuchElementException()。
以下示例程序旨在说明java.util.LinkedList.pop()方法:
示例1:
// Java code to demonstrate pop method in LinkedList
import java.util.LinkedList;
public class GfG {
// Main method
public static void main(String[] args)
{
// Creating a LinkedList object to represent a stack.
LinkedList stack = new LinkedList<>();
// Pushing an element in the stack
stack.push("Geeks");
// Pushing an element in the stack
stack.push("for");
// Pop an element from stack
String s = stack.pop();
// Printing the popped element.
System.out.println(s);
// Pushing an element in the stack
stack.push("Geeks");
// Printing the complete stack.
System.out.println(stack);
}
}
输出:
for
[Geeks, Geeks]
示例2:
// Java code to demonstrate pop method in LinkedList
import java.util.LinkedList;
public class GfG {
// Main method
public static void main(String[] args)
{
// Creating a LinkedList object to represent a stack.
LinkedList stack = new LinkedList<>();
// Pushing an element in the stack
stack.push(10);
// Pushing an element in the stack
stack.push(20);
// Pop an element from stack
Integer ele = stack.pop();
// Printing the popped element.
System.out.println(ele);
// Pop an element from stack
ele = stack.pop();
// Printing the popped element.
System.out.println(ele);
// Throws NoSuchElementException
ele = stack.pop();
// Throwsca runtime exception
System.out.println(ele);
// Printing the complete stack.
System.out.println(stack);
}
}
输出:
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)