一、迭代法
运行结果
执行结果:通过
执行用时:0 ms, 在所有 Java 提交中击败了100.00%的用户
内存消耗:36.9 MB, 在所有 Java 提交中击败了49.11%的用户
代码与注释
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
// 迭代法
class Solution {
public ListNode reverseList(ListNode head) {
ListNode pre = null;
while (head != null)
{
// 当前节点的下一个节点暂存,防止修改当前节点后找不到。
ListNode tmp = head.next;
// 修改当前节点指向上一个节点
head.next = pre;
// 更新pre为当前节点
pre = head;
// 将head更新为下一个节点,方便往后遍历
head = tmp;
}
return pre;
}
}
做题体会
- 基本思路是在遍历单向链表的过程中,修改当前节点的指向为上一个节点pre,需要注意的是,修改当前节点head的指向之前,需要先存储其下一个节点的地址到tmp中,防止修改后,无法向后遍历。
- pre节点初始化为null,当遍历到最后,当前节点指向链表末尾,此时停止循环,pre指向的就是反转链表的头部。
- 链表长度为n,此迭代法的时间复杂度为O(n),空间复杂为O(1),存储变量的空间与n无关。
- 循环停止条件:head == null,即遍历到链表的末尾。
二、递归法
执行结果:通过
执行用时 :0 ms, 在所有 Java 提交中击败了100.00%的用户
内存消耗 :37.1 MB, 在所有 Java 提交中击败了42.91%的用户
代码与注释
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
// 递归法
class Solution {
public ListNode reverseList(ListNode head) {
// 基线条件
if (head == null || head.next == null) return head;
// 递归
ListNode p = reverseList(head.next);
// 将当前节点的下一个节点head.next的指向head.next.next改成当前节点
head.next.next = head;
// 将原指向断开为null,只保留反向的指向。
head.next = null;
return p;
}
}
做题体会
- 基本思路是将当前节点的下一个节点的指向改为当前节点,即head.next.next = head,并将原指向断开,改为指向null,即head.next = null。
- 基线条件是当前节点或者其指向为null,则返回当前节点。
- 时间复杂度是O(n),空间复杂度是O(n),递归的需要深度为n的堆栈。