Java中双向链表
时间: 2023-06-28 09:06:06 浏览: 92
Java实现双向链表
在Java中,可以通过自定义类来实现双向链表的实现。
首先,我们需要定义一个双向链表节点类,它包含了前驱节点、后继节点和节点值:
```java
public class Node<T> {
public Node<T> prev;
public Node<T> next;
public T value;
public Node(Node<T> prev, Node<T> next, T value) {
this.prev = prev;
this.next = next;
this.value = value;
}
}
```
然后,我们可以定义一个双向链表类,它包含了头节点和尾节点,以及一些基本的操作方法:
```java
public class DoublyLinkedList<T> {
private Node<T> head;
private Node<T> tail;
private int size;
public DoublyLinkedList() {
head = null;
tail = null;
size = 0;
}
public boolean isEmpty() {
return size == 0;
}
public int size() {
return size;
}
public void addFirst(T value) {
Node<T> newNode = new Node<>(null, head, value);
if (head == null) {
tail = newNode;
} else {
head.prev = newNode;
}
head = newNode;
size++;
}
public void addLast(T value) {
Node<T> newNode = new Node<>(tail, null, value);
if (tail == null) {
head = newNode;
} else {
tail.next = newNode;
}
tail = newNode;
size++;
}
public T removeFirst() {
if (head == null) {
throw new NoSuchElementException();
}
T value = head.value;
head = head.next;
if (head == null) {
tail = null;
} else {
head.prev = null;
}
size--;
return value;
}
public T removeLast() {
if (tail == null) {
throw new NoSuchElementException();
}
T value = tail.value;
tail = tail.prev;
if (tail == null) {
head = null;
} else {
tail.next = null;
}
size--;
return value;
}
public void insert(int index, T value) {
if (index < 0 || index > size) {
throw new IndexOutOfBoundsException();
}
if (index == 0) {
addFirst(value);
} else if (index == size) {
addLast(value);
} else {
Node<T> node = getNode(index);
Node<T> newNode = new Node<>(node.prev, node, value);
node.prev.next = newNode;
node.prev = newNode;
size++;
}
}
public T remove(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException();
}
if (index == 0) {
return removeFirst();
} else if (index == size - 1) {
return removeLast();
} else {
Node<T> node = getNode(index);
node.prev.next = node.next;
node.next.prev = node.prev;
size--;
return node.value;
}
}
public T get(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException();
}
return getNode(index).value;
}
private Node<T> getNode(int index) {
Node<T> node = null;
if (index < size / 2) {
node = head;
for (int i = 0; i < index; i++) {
node = node.next;
}
} else {
node = tail;
for (int i = size - 1; i > index; i--) {
node = node.prev;
}
}
return node;
}
}
```
这样,我们就实现了一个双向链表类,可以用来存储任意类型的数据。
阅读全文