java链表如何实现
Java链表实现方法
链表是一种线性数据结构,由节点组成,每个节点包含数据和指向下一个节点的引用。在Java中,链表可以通过自定义类或使用内置的LinkedList类来实现。
自定义链表实现
定义一个节点类Node,包含数据域和指向下一个节点的引用:
class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
创建链表类LinkedList,包含基本的操作方法:
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提供了java.util.LinkedList类,可以直接使用:

import java.util.LinkedList;
public class Main {
public static void main(String[] args) {
LinkedList<Integer> list = new LinkedList<>();
// 添加元素
list.add(1);
list.addFirst(0);
list.addLast(2);
// 删除元素
list.removeFirst();
list.removeLast();
// 遍历链表
for (Integer num : list) {
System.out.println(num);
}
}
}
链表常见操作的时间复杂度
- 插入/删除头部节点:O(1)
- 插入/删除尾部节点:O(n)(需遍历整个链表)
- 访问指定位置元素:O(n)
- 搜索元素:O(n)
链表适合频繁插入和删除操作的场景,但随机访问性能不如数组。






