帮我用Java写个双链表
时间: 2024-05-01 20:17:23 浏览: 23
好的,我可以为您提供Java代码实现双链表。以下是实现代码:
```java
public class DoublyLinkedList<T> {
private Node<T> head;
private Node<T> tail;
private int size;
// 内部类定义节点
private static class Node<T> {
T data;
Node<T> prev;
Node<T> next;
Node(T element, Node<T> prev, Node<T> next) {
this.data = element;
this.prev = prev;
this.next = next;
}
}
// 添加一个元素到链表尾部
public void add(T element) {
Node<T> tmp = new Node<>(element, tail, null);
if (tail != null) {
tail.next = tmp;
}
tail = tmp;
if (head == null) {
head = tmp;
}
size++;
}
// 移除链表中指定位置的元素
public void remove(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
}
Node<T> cur = head;
for (int i = 0; i < index; i++) {
cur = cur.next;
}
if (cur.prev != null) {
cur.prev.next = cur.next;
} else {
head = cur.next;
}
if (cur.next != null) {
cur.next.prev = cur.prev;
} else {
tail = cur.prev;
}
size--;
}
// 获取链表中指定位置的元素
public T get(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
}
Node<T> cur = head;
for (int i = 0; i < index; i++) {
cur = cur.next;
}
return cur.data;
}
// 获取链表的长度
public int getSize() {
return size;
}
// 判断链表是否为空
public boolean isEmpty() {
return size == 0;
}
}
```
您可以根据需求使用这个双链表的实现代码。
相关推荐
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)