文章目录
1. 题库出处:
-
反转一个单链表。
-
示例:
输入: 1->2->3->4->NULL
输出: 4->3->2->1->NULL
2. 直接上递归代码
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) return head;
// 找到新的头节点
ListNode newHead = reverseList(head.next);
// 交换两个节点
head.next.next = head;
head.next = null;
return newHead;
}
3. 递归代码图解分析
3.1 递归代码分析, 原理就相当于将函数代码分别代替对应的函数
// 找到新的头节点
ListNode newHead = reverseList(head.next);
// 这句话就相当于
ListNode newHead = {
if (head == null || head.next == null) return head;
// 找到新的头节点
ListNode newHead = reverseList(head.next);
// 交换两个节点
head.next.next = head;
head.next = null;
return newHead;
}
3.2 以此类推, 就可以得到以下全部代码
// 这行代码暂时忽略
if (head == null || head.next == null) return head;
// [1, 2, 3, 4] -> [4, 3, 2, 1]
// 四个节点分别是head1, head2, head3, head4
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) return head;
// head 1
ListNode newHead = {
// head2
ListNode newHead = {
// head3
// ListNode newHead = reverseList(head.next); // 因为head4.next = null, 所以这句话就相当于
ListNode newHead = head4;
// 让head4的next -> head3
// head3 -> null;
head3.next.next = head3;
head3.next = null;
return newHead;
};;
head2.next.next = head2;
head2.next = null;
return newHead;
};
head1.next.next = head1;
head1.next = null;
return newHead;
}
3.3 那这行代码做了什么操作呢?
// 找到新的头节点
ListNode newHead = reverseList(head.next);
3.4 那这两行代码做了什么操作
// 让head4的next -> head3
// head3 -> null;
head3.next.next = head3;
head3.next = null;
- 依次类推就会得到