链表反转的递归实现 - LeetCode - 206. reverseList Linked List (Easy)

LeetCode中文 | 英文
206. 反转链表 | 206. reverseList Linked List (Easy)

Given the head of a singly linked list, reverseList the list, and return the reverseListd list.

链表反转可以通过头插法实现,较为简单,此处仅讨论其递归实现。

/* Definition for singly-linked list. */
public class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
class Solution {
    public ListNode reverseList(ListNode head) {
        if(head == null || head.next == null){
            return head;
        }
        ListNode last = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return last;
    }
}

根据结点定义,易知,这是无头结点的单链表
递归终止条件:无结点或仅剩唯一结点。

下面以反转1→2→3→4→5为例分析。

先从宏观上分析:

reverseList(2):将2——5反转。

此时,链表结构为:

稍后讨论reveseList(2)为什么返回的是这个结构。

1(head)→2←3←4←5(last)
        ↓     
       null

此时,2~5已经完成逆序,只需要再把1加入到序列中即可。

此时,head=1, head→next=2.

令head→next→next = head(原来是2→next=null,现在是2→next=head),head→next=null。此时,链表结构为:

1(head)←2←3←4←5(last)
 ↓            
null         

此时,链表完成反转,头结点为last。

下面做详细分析:

reverseList(2)→reverseList(3)→reverseList(4)→reverseList(5)

reverseList(5):

∵ head = 5; head→next = null;

∴ return

reverseList(4):

​ last = reverseList(5) = 5;

此时,链表结构为:

1→2→3→4(currentHead)→5(last)→null

继续执行。reverseList(4)返回时,链表结构为:

1→2→3→4(currentHead)←5(last)
        ↓
       null

reverseList(3)开始执行时,链表结构为:

1→2→3(currentHead)→4←5(last)
                   ↓
                  null

reverseList(3)返回时,链表结构为:

1→2→3(currentHead)←4←5(last)
     ↓
    null

所以,reverseList(2)返回时,链表结构为:

1→2(currentHead←3←4←5(last)
     ↓
    null

世界线收束,分析完毕。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值