leetcode题解-92. Reverse Linked List II

本文介绍了一种链表数据结构中的高级操作——局部反转。该操作能在原地且仅通过一次遍历实现从位置m到n的链表部分的反转。文章提供了一个具体的Java实现示例,并解释了其工作原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Reverse a linked list from position m to n. Do it in-place and in one-pass.

For example:
Given 1->2->3->4->5->NULL, m = 2 and n = 4,

return 1->4->3->2->5->NULL.

Note:
Given m, n satisfy the following condition:
1 ? m ? n ? length of list.

本题是链表翻转的进阶版,要求随意翻转链表的一部分。其实难度上并没有大很多,我们只需要找到第m和第n个节点即可,然后剩下的链表翻转操作就和之前题目的思路一样了。代码入下所示:

    public ListNode reverseBetween(ListNode head, int m, int n) {
        ListNode dummyhead = new ListNode(0);
        dummyhead.next = head;
        ListNode sublisthead = new ListNode(0);
        ListNode sublisttail = new ListNode(0);
        int count = 1;
        ListNode pre_cur = dummyhead, cur = head;
        while(count <=n){
            ListNode temp = cur.next;
            if (count < m)
                pre_cur = cur;
            else if (count == m){
                sublisttail = cur;
                sublisthead.next = cur;
            }else if (count > m){
                cur.next = sublisthead.next;
                sublisthead.next = cur;
            }
            cur = temp;
            ++count;
        }
        pre_cur.next = sublisthead.next;
        sublisttail.next = cur;
        return dummyhead.next;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值