public class DoublyLinkedList<T> {
private Node head; // 链表头节点
private Node tail; // 链表尾节点
private int size; // 链表元素个数
// 内部类Node表示链表的节点
private class Node {
T data; // 数据
Node prev; // 前一个节点的引用
Node next; // 后一个节点的引用
// 构造函数
public Node(T data, Node prev, Node next) {
this.data = data;
this.prev = prev;
this.next = next;
}
}
// 构造函数,创建空链表
public DoublyLinkedList() {
head = null;
tail = null;
size = 0;
}
// 在链表末尾插入元素
public void add(T data) {
if (tail == null) { // 如果链表为空,则新建一个节点作为头节点和尾节点
Node newNode = new Node(data, null, null);
head = newNode;
tail = newNode;
} else { // 如果链表不为空,则在尾节点后插入新节点,并更新尾节点
Node newNode = new Node(data, tail, null);
tail.next = newNode;
tail = newNode;
}
size++; // 更新链表元素个数
}
// 在指定位置插入元素
public void insert(int index, T data) {
if (index < 0 || index > size) { // 如果插入位置超出链表范围,则抛出异常
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
} else if (index == 0) { // 如果插入位置为0,则插入到头节点前,并更新头节点
Node newNode = new Node(data, null, head);
head.prev = newNode;
head = newNode;
} else if (index == size) { // 如果插入位置为链表末尾,则调用add方法插入
add(data);
} else { // 否则,在指定位置插入新节点,并更新前后节点的引用
Node curr = head;
for (int i = 0; i < index; i++) {
curr = curr.next;
}
Node newNode = new Node(data, curr.prev, curr);
curr.prev.next = newNode;
curr.prev = newNode;
size++;
}
}
// 删除指定位置的元素
public T remove(int index) {
if (index < 0 || index >= size) { // 如果删除位置超出链表范围,则抛出异常
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
} else if (index == 0) { // 如果删除头节点,则更新头节点,并将头节点的前一个节点置为null
T data = head.data;
head = head.next;
if (head != null) {
head.prev = null;
} else { // 如果链表为空,则将尾节点也置为null
tail = null;
}
size--; // 更新链表元素个数
return data; // 返回被删除元素的值
} else if (index == size - 1) { // 如果删除尾节点,则更新尾节点,并将尾节点的后一个节点置为null
T data = tail.data;
tail = tail.prev;
tail.next = null;
size--; // 更新链表元素个数
return data; // 返回被删除元素的值
} else { // 否则,找到要删除的节点,并更新前后节点的引用
Node curr = head;
for (int i = 0; i < index; i++) {
curr = curr.next;
}
T data = curr.data;
curr.prev.next = curr.next;
curr.next.prev = curr.prev;
size--; // 更新链表元素个数
return data; // 返回被删除元素的值
}
}
// 获取指定位置的元素值
public T get(int index) {
if (index < 0 || index >= size) { // 如果获取位置超出链表范围,则抛出异常
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
}
Node curr = head;
for (int i = 0; i < index; i++) {
curr = curr.next;
}
return curr.data; // 返回指定位置的元素值
}
// 获取链表元素个数
public int size() {
return size;
}
// 判断链表是否为空
public boolean isEmpty() {
return size == 0;
}
}
用Java实现双向链表
最新推荐文章于 2024-09-10 10:22:48 发布
该文章介绍了一个Java实现的双向链表(DoublyLinkedList)类,包括头节点、尾节点、节点数据、前一个节点引用和后一个节点引用。类提供了添加元素、在指定位置插入元素、删除指定位置元素以及获取元素值等方法。此外,还包含判断链表是否为空和获取元素个数的功能。
摘要由CSDN通过智能技术生成