Java 数据结构 - 链表(Linked List)

Java 中的链表(Linked List)数据结构

1. 链表的定义

链表是一种常见的线性数据结构,由一系列节点组成,每个节点包含数据字段和指向下一个节点的引用(链接)。在 Java 中,链表通常通过自定义类或使用 Java 提供的 LinkedList 类来实现。

2. 链表的类型

  1. 单向链表:每个节点只有一个指向下一个节点的引用。
  2. 双向链表:每个节点有两个引用,分别指向前一个和后一个节点。
  3. 循环链表:最后一个节点指向第一个节点,形成一个环。

3. 链表的基本结构

以单向链表为例,一个简单的节点类可以这样定义:

public class Node {
    int data;
    Node next;

    public Node(int data) {
        this.data = data;
        this.next = null;
    }
}

4. 实现一个简单的单向链表

public class LinkedList {
    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.print(current.data + " -> ");
            current = current.next;
        }
        System.out.println("NULL");
    }
}

5. 链表的常用操作

5.1 在头部插入节点

public void prepend(int data) {
    Node newNode = new Node(data);
    newNode.next = head;
    head = newNode;
}

5.2 删除节点

public void delete(int key) {
    if (head == null) return;

    if (head.data == key) {
        head = head.next;
        return;
    }

    Node current = head;
    Node prev = null;
    while (current != null && current.data != key) {
        prev = current;
        current = current.next;
    }

    if (current == null) return;

    prev.next = current.next;
}

5.3 查找节点

public boolean search(int key) {
    Node current = head;
    while (current != null) {
        if (current.data == key) {
            return true;
        }
        current = current.next;
    }
    return false;
}

6. Java 中的 LinkedList 类

Java 提供了内置的 LinkedList 类,它是双向链表的实现:

import java.util.LinkedList;

LinkedList<String> list = new LinkedList<>();
list.add("Apple");
list.add("Banana");
list.addFirst("Orange");
list.addLast("Mango");

System.out.println(list); // 输出: [Orange, Apple, Banana, Mango]

7. 链表的优缺点

优点:

  • 动态大小
  • 插入和删除操作效率高(O(1)复杂度)
  • 内存利用效率高(不需要预先分配内存)

缺点:

  • 随机访问效率低(O(n)复杂度)
  • 比数组占用更多内存(需要额外存储指针)

8. 链表 vs 数组

特性 链表 数组
大小 动态 固定
内存分配 动态 静态
插入/删除效率
随机访问效率
内存使用 较高 较低

9. 总结

链表是一种灵活的数据结构,特别适合需要频繁插入和删除操作的场景。虽然在随机访问方面不如数组,但其动态特性使其在许多应用中非常有用。理解链表的工作原理对于选择合适的数据结构和优化算法至关重要。

posted @ 2024-07-18 14:33  KenWan  阅读(93)  评论(0)    收藏  举报