在Java中实现一个高效的算法来反转链表,同时考虑内存使用和时间复杂度。
在 Java 中反转链表是一个经典的算法问题,可以通过迭代或递归的方式实现。以下是两种方法的详细实现及其分析。
迭代法
迭代法是反转链表的高效方法,其时间复杂度为 O(n),空间复杂度为 O(1),因为只需要几个额外的指针变量。
实现代码
public class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
}
}
public ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode current = head;
while (current != null) {
ListNode nextNode = current.next; // 保存下一个节点
current.next = prev; // 反转指针
prev = current; // 移动 prev
current = nextNode; // 移动 current
}
return prev; // prev 是新的头节点
}
示例分析
假设链表为 1 -> 2 -> 3 -> null:
- 初始时,
prev = null,current = 1。 - 第一次循环:
nextNode = 2,1.next = null,prev = 1,current = 2。链表状态:null <- 1 2 -> 3 -> null - 第二次循环:
nextNode = 3,2.next = 1,prev = 2,current = 3。链表状态:null <- 1 <- 2 3 -> null - 第三次循环:
nextNode = null,3.next = 2,prev = 3,current = null。链表状态:null <- 1 <- 2 <- 3 - 循环结束,返回
prev = 3,即反转后的头节点。
递归法
递归法的思路是从链表的尾部开始反转,时间复杂度为 O(n),空间复杂度为 O(n)(因为递归调用栈的深度)。
实现代码
public ListNode reverseListRecursive(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode newHead = reverseListRecursive(head.next); // 递归反转后续链表
head.next.next = head; // 反转当前节点
head.next = null; // 断开原指针
return newHead;
}
示例分析
假设链表为 1 -> 2 -> 3 -> null:
- 递归调用
reverseListRecursive(1),进入reverseListRecursive(2),再进入reverseListRecursive(3)。 3.next == null,返回3作为新的头节点。- 回到
reverseListRecursive(2):2.next.next = 2(将3指向2),2.next = null,链表状态:1 -> 2 <- 3。 - 回到
reverseListRecursive(1):1.next.next = 1(将2指向1),1.next = null,链表状态:null <- 1 <- 2 <- 3。 - 最终返回
newHead = 3。
总结
- 迭代法更适合实际应用,因为它不需要额外的栈空间,空间复杂度更低。
- 递归法代码更简洁,但当链表较长时可能引发栈溢出问题。
- 两种方法的时间复杂度均为 O(n),但递归法的空间复杂度较高。