java如何运行链表
运行链表的基本方法
在Java中,链表通常通过LinkedList类或自定义链表实现。以下是两种常见方法的详细说明。
使用Java内置的LinkedList类
Java提供了java.util.LinkedList类,可直接用于链表的创建和操作。以下是示例代码:
import java.util.LinkedList;
public class Main {
public static void main(String[] args) {
LinkedList<String> list = new LinkedList<>();
// 添加元素
list.add("A");
list.add("B");
list.addFirst("C"); // 在头部添加
list.addLast("D"); // 在尾部添加
// 遍历链表
for (String item : list) {
System.out.println(item);
}
// 删除元素
list.removeFirst();
list.removeLast();
}
}
自定义链表实现
如果需要手动实现链表,可以定义一个节点类并管理节点间的链接关系。以下是自定义链表的示例:
class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
public class CustomLinkedList {
Node head;
// 添加元素到链表尾部
public void append(int data) {
if (head == null) {
head = new Node(data);
return;
}
Node current = head;
while (current.next != null) {
current = current.next;
}
current.next = new Node(data);
}
// 打印链表
public void printList() {
Node current = head;
while (current != null) {
System.out.println(current.data);
current = current.next;
}
}
public static void main(String[] args) {
CustomLinkedList list = new CustomLinkedList();
list.append(1);
list.append(2);
list.append(3);
list.printList();
}
}
链表常见操作
链表的常见操作包括插入、删除、遍历和搜索。以下是这些操作的实现示例:

// 在指定位置插入节点
public void insert(int index, int data) {
if (index == 0) {
Node newNode = new Node(data);
newNode.next = head;
head = newNode;
return;
}
Node current = head;
for (int i = 0; i < index - 1 && current != null; i++) {
current = current.next;
}
if (current != null) {
Node newNode = new Node(data);
newNode.next = current.next;
current.next = 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;
}
}
链表的应用场景
链表适用于频繁插入和删除操作的场景,因为其时间复杂度为O(1)。相比之下,数组的插入和删除操作可能需要O(n)的时间。链表还用于实现栈、队列和其他高级数据结构。






