java 如何构建链表
构建链表的基本方法
在 Java 中,链表可以通过自定义类实现。链表由节点(Node)组成,每个节点包含数据和指向下一个节点的引用。
定义节点类
class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
链表类的基本实现
class LinkedList {
Node head;
// 在链表末尾添加节点
public void append(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
return;
}
Node current = head;
while (current.next != null) {
current = current.next;
}
current.next = newNode;
}
// 在链表头部添加节点
public void prepend(int data) {
Node newNode = new Node(data);
newNode.next = head;
head = newNode;
}
// 删除指定值的节点
public void delete(int data) {
if (head == null) return;
if (head.data == data) {
head = head.next;
return;
}
Node current = head;
while (current.next != null) {
if (current.next.data == data) {
current.next = current.next.next;
return;
}
current = current.next;
}
}
// 打印链表
public void printList() {
Node current = head;
while (current != null) {
System.out.print(current.data + " ");
current = current.next;
}
System.out.println();
}
}
使用 Java 内置的 LinkedList 类
Java 提供了内置的 LinkedList 类,位于 java.util 包中,可以直接使用。
import java.util.LinkedList;
public class Main {
public static void main(String[] args) {
LinkedList<Integer> list = new LinkedList<>();
// 添加元素
list.add(1);
list.add(2);
list.addFirst(0); // 在头部添加
list.addLast(3); // 在尾部添加
// 删除元素
list.removeFirst();
list.removeLast();
// 遍历链表
for (int num : list) {
System.out.println(num);
}
}
}
链表的常见操作
反转链表
public void reverse() {
Node prev = null;
Node current = head;
Node next;
while (current != null) {
next = current.next;
current.next = prev;
prev = current;
current = next;
}
head = prev;
}
检测链表是否有环
public boolean hasCycle() {
if (head == null) return false;
Node slow = head;
Node fast = head.next;
while (fast != null && fast.next != null) {
if (slow == fast) return true;
slow = slow.next;
fast = fast.next.next;
}
return false;
}
链表的优缺点
优点
- 动态数据结构,大小可以灵活调整
- 插入和删除操作效率高(O(1) 或 O(n))
- 不需要连续的内存空间
缺点

- 访问元素需要遍历(O(n))
- 需要额外的内存空间存储节点引用
- 缓存不友好,可能导致性能下降






