告别了链表与数组,我们来到栈的学习。
栈的常用操作主要有:
● push(E):增加一个元素E
● pop():弹出元素E
● peek():显示栈顶元素,但是不出栈
● empty():判断栈是否为空
接下来我们用链表来实现栈
class ListStack<T> {
// 定义链表
class Node<T> {
public T t; // 节点包含的数据
public Node next; // 下一个节点的引用
}
public Node<T> head; // 头指针
// 构造函数初始化头指针
ListStack() {
head = null; // 初始状态下头指针为空
}
// 入栈
public void push(T t) {
if (t == null) {
throw new NullPointerException("参数不能为空");
}
if (head == null) {
head = new Node<T>(); // 如果链表为空,创建一个新的节点作为头结点
head.t = t; // 设置新节点的数据为传入的参数
head.next = null; // 新节点的下一个节点为空
} else {
Node<T> temp = head; // 保存当前头节点的引用
head = new Node<>(); // 创建一个新节点,作为新的头节点
head.t = t; // 设置新节点的数据为传入的参数
head.next = temp; // 将新节点的下一个节点指向之前的头节点
}
}
// 出栈
public T pop() {
if (head == null) {
return null; // 如果链表为空,则返回空
}
T t = head.t; // 获取头节点的数据
head = head.next; // 将头指针指向下一个节点,实现出栈操作
return t; // 返回出栈的数据
}
// 取栈顶元素
public T peek() {
if (head == null) {
return null; // 如果链表为空,则返回空
}
T t = head.t; // 获取头节点的数据
return t; // 返回栈顶元素的数据
}
// 栈空
public boolean isEmpty() {
if (head == null)
return true; // 如果头指针为null,说明栈为空,返回true
else
return false; // 否则返回false,说明栈不为空
}
}