JAVA 100道题(14)

14.编写一个程序,使用LinkedList实现一个简单的堆栈(Stack)数据结构。

堆栈(Stack)是一种遵循后进先出(LIFO,Last In First Out)原则的数据结构。下面是一个使用Java的LinkedList类来实现堆栈的简单示例:

复制代码

java复制代码

|---|-----------------------------------------------------------------|
| | import java.util.LinkedList; |
| | |
| | public class Stack<T> { |
| | private LinkedList<T> list; |
| | |
| | public Stack() { |
| | list = new LinkedList<>(); |
| | } |
| | |
| | // 入栈操作 |
| | public void push(T item) { |
| | list.addFirst(item); |
| | } |
| | |
| | // 出栈操作 |
| | public T pop() { |
| | if (isEmpty()) { |
| | throw new RuntimeException("Stack is empty"); |
| | } |
| | return list.removeFirst(); |
| | } |
| | |
| | // 查看栈顶元素 |
| | public T peek() { |
| | if (isEmpty()) { |
| | throw new RuntimeException("Stack is empty"); |
| | } |
| | return list.getFirst(); |
| | } |
| | |
| | // 检查栈是否为空 |
| | public boolean isEmpty() { |
| | return list.isEmpty(); |
| | } |
| | |
| | // 获取栈的大小 |
| | public int size() { |
| | return list.size(); |
| | } |
| | |
| | public static void main(String[] args) { |
| | Stack<Integer> stack = new Stack<>(); |
| | |
| | // 入栈操作 |
| | stack.push(1); |
| | stack.push(2); |
| | stack.push(3); |
| | |
| | System.out.println("Stack size: " + stack.size()); |
| | |
| | // 查看栈顶元素 |
| | System.out.println("Top element: " + stack.peek()); |
| | |
| | // 出栈操作 |
| | System.out.println("Popped element: " + stack.pop()); |
| | |
| | System.out.println("Stack size after pop: " + stack.size()); |
| | } |
| | } |

在这个程序中,我们定义了一个泛型类Stack<T>,它使用LinkedList作为内部存储结构。push方法用于将元素添加到栈顶,pop方法用于从栈顶移除并返回元素,peek方法用于查看栈顶元素但不移除它,isEmpty方法用于检查栈是否为空,size方法用于获取栈的大小。

在main方法中,我们创建了一个Stack<Integer>对象,并进行了入栈、查看栈顶元素和出栈操作

相关推荐
用户019027581611 小时前
天勤 tqsdk 能做 A 股行情吗?期货强项与股票数据选型
python
考虑考虑1 小时前
JDK27中的Set.ofLazy
java·后端·java ee
文丑颜不良啊1 小时前
LeetCode2841~2860题目解析
java·leetcode
小南家的青蛙1 小时前
Tomcat与Jetty深度对比
java·tomcat·jetty
2601_967979122 小时前
pip在Python中的9个必须知道的用法
python·pip·版本控制·包管理工具·requirements.txt
Funlang2 小时前
在 Windows 95 上跑 Fun
windows
曲径海盗2 小时前
【Python 学习第 58 天】列表方法
python·学习笔记·编程入门
乌暮3 小时前
Spring AOP 与 Spring 事务:用大白话彻底理解原理与实践
java·数据库·spring boot·后端·sql·学习·spring
DeepVisionary3 小时前
Runway开源机器人大模型Praxis-1,推演延迟压到62毫秒
python·自动化
YDS8293 小时前
Small Spring IOC篇:容器事件及其监听器
java·spring