02-反转链表-递归

1. 题库出处:

LeetCode 反转链表地址

  • 反转一个单链表。

  • 示例:

输入: 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;

在这里插入图片描述

  • 依次类推就会得到
    在这里插入图片描述
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值