public class DoubleLinkedList<T> {
private Node<T> head;
private Node<T> tail;
public void insert(T data) {
Node<T> newNode = new Node<>(data);
if (head == null) {
head = newNode;
tail = newNode;
} else {
tail.next = newNode;
newNode.prev = tail;
tail = newNode;
}
}
public void delete(T data) {
Node<T> current = head;
while (current != null) {
if (current.data.equals(data)) {
if (current.prev != null) {
current.prev.next = current.next;
} else {
head = current.next;
}
if (current.next != null) {
current.next.prev = current.prev;
} else {
tail = current.prev;
}
return;
}
current = current.next;
}
}
public Node<T> search(T data) {
Node<T> current = head;
while (current != null) {
if (current.data.equals(data)) {
return current;
}
current = current.next;
}
return null;
}
public void modify(int index, T newData) {
Node<T> current = head;
int i = 0;
while (current != null && i < index) {
current = current.next;
i++;
}
if (current != null) {
current.data = newData;
}
}
public void traverse() {
Node<T> current = head;
while (current != null) {
System.out.print(current.data + " ");
current = current.next;
}
}
private static class Node<T> {
private T data;
private Node<T> prev;
private Node<T> next;
public Node(T data) {
this.data = data;
}
}
}
public class DoubleLinkedListTest {
public static void main(String[] args) {
DoubleLinkedList<Integer> list = new DoubleLinkedList<>();
list.insert(1);
list.insert(2);
list.insert(3);
list.insert(4);
list.traverse(); // 输出:1 2 3 4
list.delete(3);
list.traverse(); // 输出:1 2 4
System.out.println(list.search(2).data); // 输出:2
list.modify(1, 5);
list.traverse(); // 输出:1 5 4
}
}