阅读量:0
在Java中,可以使用自定义的双向链表类来实现双向链表。以下是一个简单的双向链表的实现示例:
public class DoublyLinkedList<T> { private Node<T> head; // 链表头节点 private Node<T> tail; // 链表尾节点 // 链表节点类 private static class Node<T> { private T data; // 节点数据 private Node<T> prev; // 前一个节点引用 private Node<T> next; // 后一个节点引用 public Node(T data) { this.data = data; } } // 在链表末尾添加节点 public void add(T data) { Node<T> newNode = new Node<>(data); if (head == null) { head = newNode; tail = newNode; } else { newNode.prev = tail; tail.next = newNode; tail = newNode; } } // 在链表指定位置插入节点 public void insert(int index, T data) { if (index < 0 || index > size()) { throw new IndexOutOfBoundsException(); } Node<T> newNode = new Node<>(data); if (index == 0) { if (head == null) { head = newNode; tail = newNode; } else { newNode.next = head; head.prev = newNode; head = newNode; } } else if (index == size()) { tail.next = newNode; newNode.prev = tail; tail = newNode; } else { Node<T> current = getNode(index); newNode.prev = current.prev; newNode.next = current; current.prev.next = newNode; current.prev = newNode; } } // 获取链表指定位置的节点 private Node<T> getNode(int index) { if (index < 0 || index >= size()) { throw new IndexOutOfBoundsException(); } Node<T> current = head; for (int i = 0; i < index; i++) { current = current.next; } return current; } // 移除链表指定位置的节点 public void remove(int index) { if (index < 0 || index >= size()) { throw new IndexOutOfBoundsException(); } if (index == 0) { head = head.next; if (head == null) { tail = null; } else { head.prev = null; } } else if (index == size() - 1) { tail = tail.prev; tail.next = null; } else { Node<T> current = getNode(index); current.prev.next = current.next; current.next.prev = current.prev; } } // 获取链表大小 public int size() { int count = 0; Node<T> current = head; while (current != null) { count++; current = current.next; } return count; } }
以上是一个简单的双向链表类的实现示例,你可以使用该类来创建双向链表并进行插入、移除、获取节点等操作。