當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。