目录
一,基本知识
内存空间是所有程序的公共资源,在一个复杂的系统运行环境下,空闲的内存空间可能散落在内存各处。我们知道,存储数组的内存空间必须是连续的,而当数组非常大时,内存可能无法提供如此大的连续空间。此时链表的灵活性优势就体现出来了。
链表(linked list)是一种线性数据结构,其中的每个元素都是一个节点对象,各个节点通过“引用”相连接。引用记录了下一个节点的内存地址,通过它可以从当前节点访问到下一个节点。
链表的设计使得各个节点可以分散存储在内存各处,它们的内存地址无须连续。
链表的组成单位是节点(node)对象。每个节点都包含两项数据:节点的“值”和指向下一节点的“引用”。
- 链表的首个节点被称为“头节点”,最后一个节点被称为“尾节点”。
- 尾节点指向的是“空”,它在 Java、C++ 和 Python 中分别被记为
null
、nullptr
和None
。 - 在 C、C++、Go 和 Rust 等支持指针的语言中,上述“引用”应被替换为“指针”。
如以下代码所示,链表节点 ListNode
除了包含值,还需额外保存一个引用(指针)。因此在相同数据量下,链表比数组占用更多的内存空间。
/* 链表节点类 */
class ListNode {
int val; // 节点值
ListNode next; // 指向下一节点的引用
ListNode(int x) { val = x; } // 构造函数
}
二,链表的常用操作
1.链表的初始化
建立链表分为两步,第一步是初始化各个节点对象,第二步是构建节点之间的引用关系。初始化完成后,我们就可以从链表的头节点出发,通过引用指向 next
依次访问所有节点。
/* 初始化链表 1 -> 3 -> 2 -> 5 -> 4 */
// 初始化各个节点
ListNode n0 = new ListNode(1);
ListNode n1 = new ListNode(3);
ListNode n2 = new ListNode(2);
ListNode n3 = new ListNode(5);
ListNode n4 = new ListNode(4);
// 构建节点之间的引用
n0.next = n1;
n1.next = n2;
n2.next = n3;
n3.next = n4;
数组整体是一个变量,比如数组 nums
包含元素 nums[0]
和 nums[1]
等,而链表是由多个独立的节点对象组成的。我们通常将头节点当作链表的代称,比如以上代码中的链表可记作链表 n0
。
2.插入节点
在链表中插入节点非常容易。如图 4-6 所示,假设我们想在相邻的两个节点 n0
和 n1
之间插入一个新节点 P
,则只需改变两个节点引用(指针)即可,时间复杂度为 O(1) 。
- 创建新节点: 首先,你需要为新的数据项创建一个新的链表节点。这通常涉及到分配内存并设置节点的数据成员。
- 定位插入位置: 你需要遍历链表直到找到插入位置的前一个节点。这是因为你需要修改这个前驱节点的next指针指向新节点,同时新节点的next指针指向原本应该在插入位置的节点。
- 插入新节点: 更新前驱节点的next指针使其指向新节点,并更新新节点的next指针使其指向原本应该在插入位置的节点。
- 处理边界情况: 如果插入位置是在链表的头部,那么新节点将成为新的头节点,并且其next指针应指向原来的头节点。如果插入位置是在链表的尾部,那么你可能需要额外的逻辑来处理这种情况,例如维护一个指向尾节点的指针。
相比之下,在数组中插入元素的时间复杂度为 O(n) ,在大数据量下的效率较低。
public class LinkedList {
private Node head; // 链表的头节点
// 定义链表节点
private static class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
// 在链表的给定位置插入一个新节点
public void insertAtPosition(int position, int data) {
Node newNode = new Node(data);
// 如果链表为空或插入位置为1,则新节点成为头节点
if (position == 1 || head == null) {
newNode.next = head;
head = newNode;
} else {
Node current = head;
int count = 1;
// 遍历链表直到找到插入位置的前一个节点
while (count < position - 1 && current.next != null) {
current = current.next;
count++;
}
// 检查是否越界
if (count < position - 1) {
System.out.println("Invalid position");
return;
}
// 插入节点
newNode.next = current.next;
current.next = newNode;
}
}
// 打印链表的所有元素
public void printList() {
Node current = head;
while (current != null) {
System.out.print(current.data + " -> ");
current = current.next;
}
System.out.println("null");
}
// 测试插入功能
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.insertAtPosition(1, 1); // 插入第一个元素
list.insertAtPosition(2, 2); // 在第一个元素后插入第二个元素
list.insertAtPosition(2, 10); // 在1和2之间插入10
list.printList(); // 输出链表
}
}
3.删除节点
在链表中删除节点也非常方便,只需改变一个节点的引用(指针)即可。
public class LinkedList {
private Node head; // 链表的头节点
// 定义链表节点
private static class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
// 删除具有特定值的节点
public boolean deleteNode(int value) {
Node current = head;
Node previous = null;
// 如果头节点就是要删除的节点
if (current != null && current.data == value) {
head = current.next; // 新的头节点是当前节点的下一个节点
return true;
}
// 寻找要删除的节点,同时跟踪前一个节点
while (current != null && current.data != value) {
previous = current;
current = current.next;
}
// 如果链表中没有找到要删除的节点
if (current == null) {
return false;
}
// 跳过要删除的节点
previous.next = current.next;
return true;
}
// 打印链表的所有元素
public void printList() {
Node current = head;
while (current != null) {
System.out.print(current.data + " -> ");
current = current.next;
}
System.out.println("null");
}
// 测试删除节点功能
public static void main(String[] args) {
LinkedList list = new LinkedList();
// 初始化链表
list.head = new Node(1);
list.head.next = new Node(2);
list.head.next.next = new Node(3);
list.head.next.next.next = new Node(4);
list.head.next.next.next.next = new Node(5);
list.printList(); // 输出链表
// 删除值为3的节点
boolean deleted = list.deleteNode(3);
if (deleted) {
System.out.println("Node with value 3 was deleted.");
} else {
System.out.println("Node with value 3 was not found.");
}
list.printList(); // 再次输出链表,确认删除
}
}
4.访问节点
在链表中访问节点的效率较低。如上一节所述,我们可以在 O(1) 时间下访问数组中的任意元素。链表则不然,程序需要从头节点出发,逐个向后遍历,直至找到目标节点。也就是说,访问链表的第 i个节点需要循环 i−1 轮,时间复杂度为 O(n) 。
public class LinkedList {
private Node head; // 链表的头节点
// 定义链表节点
private static class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
// 根据索引访问链表中的节点
public Node getNodeByIndex(int index) {
Node current = head;
int currentIndex = 0;
while (current != null) {
if (currentIndex == index) {
return current; // 返回找到的节点
}
current = current.next;
currentIndex++;
}
return null; // 如果没有找到,则返回null
}
// 打印链表的所有元素
public void printList() {
Node current = head;
while (current != null) {
System.out.print(current.data + " -> ");
current = current.next;
}
System.out.println("null");
}
// 测试访问节点功能
public static void main(String[] args) {
LinkedList list = new LinkedList();
// 初始化链表
list.head = new Node(1);
list.head.next = new Node(2);
list.head.next.next = new Node(3);
list.head.next.next.next = new Node(4);
list.head.next.next.next.next = new Node(5);
list.printList(); // 输出链表
// 访问索引为2的节点
Node accessedNode = list.getNodeByIndex(2);
if (accessedNode != null) {
System.out.println("Accessed node at index 2 with value: " + accessedNode.data);
} else {
System.out.println("Node not found.");
}
}
}
5.查找节点
遍历链表,查找其中值为 target
的节点,输出该节点在链表中的索引。此过程也属于线性查找。代码如下所示:
public class LinkedList {
private Node head; // 链表的头节点
// 定义链表节点
private static class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
// 查找具有特定值的节点
public Node findNode(int value) {
Node current = head;
while (current != null) {
if (current.data == value) {
return current; // 返回找到的节点
}
current = current.next;
}
return null; // 如果没有找到,则返回null
}
// 打印链表的所有元素
public void printList() {
Node current = head;
while (current != null) {
System.out.print(current.data + " -> ");
current = current.next;
}
System.out.println("null");
}
// 测试查找功能
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.head = new Node(1);
list.head.next = new Node(2);
list.head.next.next = new Node(3);
list.head.next.next.next = new Node(4);
list.head.next.next.next.next = new Node(5);
list.printList(); // 输出链表
Node foundNode = list.findNode(3);
if (foundNode != null) {
System.out.println("Found node with value: " + foundNode.data);
} else {
System.out.println("Node not found.");
}
}
}
三,数组与链表的比较
数组 链表
存储方式 连续内存空间 分散内存空间
容量拓展 长度不可变 可灵活拓展
内存效率 内存占用内存少,可能浪费空间 元素占用多
访问元素 O(1) O(n)
添加元素 O(n) O(1)
删除元素 O(n) O(1)
四,常见的链表类型内存
- 单向链表:即前面介绍的普通链表。单向链表的节点包含值和指向下一节点的引用两项数据。我们将首个节点称为头节点,将最后一个节点称为尾节点,尾节点指向空
None
。- 环形链表:如果我们令单向链表的尾节点指向头节点(首尾相接),则得到一个环形链表。在环形链表中,任意节点都可以视作头节点。
- 双向链表:与单向链表相比,双向链表记录了两个方向的引用。双向链表的节点定义同时包含指向后继节点(下一个节点)和前驱节点(上一个节点)的引用(指针)。相较于单向链表,双向链表更具灵活性,可以朝两个方向遍历链表,但相应地也需要占用更多的内存空间。
五,链表类型的典型运用
单向链表通常用于实现栈、队列、哈希表和图等数据结构。
- 栈与队列:当插入和删除操作都在链表的一端进行时,它表现的特性为先进后出,对应栈;当插入操作在链表的一端进行,删除操作在链表的另一端进行,它表现的特性为先进先出,对应队列。
- 哈希表:链式地址是解决哈希冲突的主流方案之一,在该方案中,所有冲突的元素都会被放到一个链表中。
- 图:邻接表是表示图的一种常用方式,其中图的每个顶点都与一个链表相关联,链表中的每个元素都代表与该顶点相连的其他顶点。
双向链表常用于需要快速查找前一个和后一个元素的场景。
- 高级数据结构:比如在红黑树、B 树中,我们需要访问节点的父节点,这可以通过在节点中保存一个指向父节点的引用来实现,类似于双向链表。
- 浏览器历史:在网页浏览器中,当用户点击前进或后退按钮时,浏览器需要知道用户访问过的前一个和后一个网页。双向链表的特性使得这种操作变得简单。
- LRU 算法:在缓存淘汰(LRU)算法中,我们需要快速找到最近最少使用的数据,以及支持快速添加和删除节点。这时候使用双向链表就非常合适。
环形链表常用于需要周期性操作的场景,比如操作系统的资源调度。
- 时间片轮转调度算法:在操作系统中,时间片轮转调度算法是一种常见的 CPU 调度算法,它需要对一组进程进行循环。每个进程被赋予一个时间片,当时间片用完时,CPU 将切换到下一个进程。这种循环操作可以通过环形链表来实现。
- 数据缓冲区:在某些数据缓冲区的实现中,也可能会使用环形链表。比如在音频、视频播放器中,数据流可能会被分成多个缓冲块并放入一个环形链表,以便实现无缝播放。