Java中的Stack pop()方法
Java中的java.util.Stack.pop()方法用于从堆栈中弹出一个元素。该元素从堆栈的顶部弹出并从堆栈中删除。
语法:
STACK.pop()
参数: 该方法不接受任何参数。
返回值: 该方法返回堆栈顶部的元素,然后将其删除。
异常: 如果堆栈为空,则抛出EmptyStackException。
以下程序说明了Java中的java.util.Stack.pop()方法:
程序1:
// Java code to illustrate pop()
import java.util.*;
public class StackDemo {
public static void main(String args[])
{
// Creating an empty Stack
Stack<String> STACK = new Stack<String>();
// Use add() method to add elements
STACK.push("Welcome");
STACK.push("To");
STACK.push("Geeks");
STACK.push("For");
STACK.push("Geeks");
// Displaying the Stack
System.out.println("Initial Stack: " + STACK);
// Removing elements using pop() method
System.out.println("Popped element: " +
STACK.pop());
System.out.println("Popped element: " +
STACK.pop());
// Displaying the Stack after pop operation
System.out.println("Stack after pop operation "
+ STACK);
}
}
程序2:
// Java code to illustrate pop()
import java.util.*;
public class StackDemo {
public static void main(String args[])
{
// Creating an empty Stack
Stack<Integer> STACK = new Stack<Integer>();
// Use add() method to add elements
STACK.push(10);
STACK.push(15);
STACK.push(30);
STACK.push(20);
STACK.push(5);
// Displaying the Stack
System.out.println("Initial Stack: " + STACK);
// Removing elements using pop() method
System.out.println("Popped element: " +
STACK.pop());
System.out.println("Popped element: " +
STACK.pop());
// Displaying the Stack after pop operation
System.out.println("Stack after pop operation "
+ STACK);
}
}
输出:
Initial Stack: [10, 15, 30, 20, 5]
Popped element: 5
Popped element: 20
Stack after pop operation [10, 15, 30]