LeetCode 92. 反转链表 II

本文探讨了两种不同的算法技巧——双指针和递归,用于解决链表中特定区间反转的问题。第一种方法利用迭代实现,而第二种则是通过递归巧妙地调整节点连接。实例代码展示了如何在 ListNode 类中操作,适合初学者理解链表操作的高级技巧。
摘要由CSDN通过智能技术生成

第一种方法,使用双指针,头插法

class Solution {
    public ListNode reverseBetween(ListNode head, int left, int right) {
        // 设置 dummyNode 是这一类问题的一般做法
        ListNode dummyNode = new ListNode(-1);
        dummyNode.next = head;
        ListNode pre = dummyNode;
        for (int i = 0; i < left - 1; i++) {
            pre = pre.next;
        }
        ListNode cur = pre.next;
        ListNode next;
        for (int i = 0; i < right - left; i++) {
            next = cur.next;
            cur.next = next.next;
            next.next = pre.next;
            pre.next = next;
        }
        return dummyNode.next;
    }
}

第二种,使用递归实现

class Solution {
    static ListNode successor = null;
    public static ListNode reverseN(ListNode head, int n) {
        if(n==1){
            successor=head.next;
            return head;
        }
        ListNode last=reverseN(head.next,n-1);
        head.next.next=head;
        head.next=successor;
        return last;
    }
    public static ListNode reverseBetween(ListNode head, int m, int n) {
        if(m==1){
            return reverseN(head,n);
        }
        head.next=reverseBetween(head.next,m-1,n-1);

        return head;
    }

    public static void main(String[] args) {
        ListNode listNode1=new ListNode(1);
        ListNode listNode2=new ListNode(2);
        ListNode listNode3=new ListNode(3);
        ListNode listNode4=new ListNode(4);

        listNode1.next=listNode2;
        listNode2.next=listNode3;
        listNode3.next=listNode4;
        listNode4.next=null;

        ListNode result=reverseBetween(listNode1,1,4);

        while (result!=null){
            System.out.print(result.val+"-->");
            result=result.next;
        }
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值