当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java LinkedList pop()用法及代码示例


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<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(); 
  
        // 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)


相关用法


注:本文由纯净天空筛选整理自ShivamKD大神的英文原创作品 LinkedList pop() Method in Java。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。