在Java中,可以使用peek()方法来获取栈顶元素。peek()方法会返回栈顶元素但不会将其从栈中移除。以下是一个示例:
import java.util.Stack;
public class Main {
public static void main(String[] args) {
Stack<Integer> stack = new Stack<>();
stack.push(1);
stack.push(2);
stack.push(3);
int topElement = stack.peek();
System.out.println("栈顶元素为:" + topElement);
}
}
输出结果为:
栈顶元素为:3
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读:c++ stack怎么获取栈顶元素