Day 11 leetcode 反转链表的一部分

Day 11

题目:反转链表的一部分

leetcode链接:反转链表II
要点:递归

反转链表前N个节点

ListNode successor = null; // 后驱节点
// 反转以 head 为起点的 n 个节点,返回新的头结点
ListNode reverseN(ListNode head, int n) {
    if (n == 1) {
        // 记录第 n + 1 个节点
        successor = head.next;
        return head;
    }
    // 以 head.next 为起点,需要反转前 n - 1 个节点
    ListNode last = reverseN(head.next, n - 1);

    head.next.next = head;
    // 让反转之后的 head 节点和后面的节点连起来
    head.next = successor;
    return last;
}

1、Java

class Solution {
    public ListNode reverseBetween(ListNode head, int left, int right) {
        if(left == 1){
            // 相当于反转前right个节点
            return reverseN(head, right);
        }
        // 前进到反转的起点触发base case
        head.next = reverseBetween(head.next, left - 1, right - 1);
        return head;
    }

    ListNode successor = null; // 后驱节点
    // 反转以head为起点的n个节点,返回新的头节点
    public ListNode reverseN(ListNode head, int n){
        if(n == 1){
            // 记录第n+1个节点
            successor = head.next;
            return head;
        }
        // 以head.next为起点,需要反转前n-1个节点
        ListNode last = reverseN(head.next, n-1);
        head.next.next = head;
        // 让反转之后的head节点和后面的节点连起来
        head.next = successor;
        return last;
    }
}

2、python

class Solution:
    def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]:
        if left == 1:
            return Solution.reverseN(self, head, right)
        head.next = Solution.reverseBetween(self, head.next, left - 1, right - 1)
        return head

    def reverseN(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
        global successor
        if n == 1:
            successor = head.next
            return head
        last = Solution.reverseN(self, head.next, n - 1)
        head.next.next = head
        head.next = successor
        return last
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值