java pop_Java Stack pop()用法及代码示例

Java中的Java.util.Stack.pop()方法用于从堆栈中弹出元素。该元素从堆栈顶部弹出,并从堆栈顶部移除。

用法:

STACK.pop()

参数:该方法不带任何参数。

返回值:此方法返回出现在堆栈顶部的元素,然后将其删除。

异常:如果堆栈为空,则抛出方法EmptyStackException。

以下示例程序旨在说明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 STACK = new Stack();

// 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 peration "

+ STACK);

}

}

输出:

Initial Stack: [Welcome, To, Geeks, For, Geeks]

Popped element: Geeks

Popped element: For

Stack after pop peration [Welcome, To, Geeks]

示例2:

// Java code to illustrate pop()

import java.util.*;

public class StackDemo {

public static void main(String args[])

{

// Creating an empty Stack

Stack STACK = new Stack();

// 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]

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值