Java LinkedList pop()方法

Java LinkedList pop()方法

java.util.LinkedList.pop()方法用于从LinkedList所代表的堆栈中移除并返回顶部元素。该方法只是简单的将堆栈顶部的元素弹出。这个方法类似于LinkedList中的removeFirst方法。

语法:

LinkedListObject.pop()

参数: 该方法不接受任何参数。
返回值: 该方法返回LinkedList所代表的堆栈的第一个(以堆栈为单位)值。
异常: 如果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<String> 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<Integer> 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();
 
        // Throws a 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)

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程