public class DoubleLinkedList<T> {
private Node<T> head;
private Node<T> tail;
private class Node<T> {
T data;
Node<T> prev;
Node<T> next;
public Node(T data) {
this.data = data;
}
}
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> find(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;
}
}
}