BM2 链表内指定区间反转

在这里插入图片描述
第一种方法:比较好理解,将原数组分成三段,然后对中间链表进行反转,最后在拼接上,时间复杂度为O(n),空间复杂度为O(1)。

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {
    /**
     *
     * @param head ListNode类
     * @param m int整型
     * @param n int整型
     * @return ListNode类
     */
    public ListNode reverseBetween (ListNode head, int m, int n) {
        // write code here
        //将链表分成三部分
        // 0->m-1为一部分,m->n为一部分, n+1->null为一部分
        ListNode result = new ListNode(-1);
        result.next = head;

        //pre一直到m-1个位置
        ListNode pre = result;
        for (int i = 1; i < m; i++) {
            pre = pre.next;
        }

        //tail一直到第n个位置
        ListNode tail = pre;
        for (int i = 0; i < n - m + 1; i++) {
            tail = tail.next;
        }
        //这里保存第m个位置的数据和n+1的位置
        ListNode revertNode = pre.next;
        ListNode end = tail.next;

        pre.next = null;
        tail.next = null;
        revert(revertNode);
        pre.next = tail;
        revertNode.next = end;
        return result.next;
    }

    private void revert(ListNode head) {
        ListNode pre = null;
        ListNode next = null;
        while (head != null) {
            next = head.next;
            head.next = pre;
            pre = head;
            head = next;
        }
    }
}

第二种方法:参考牛客大佬“De梦“,一个个往前移的思想,时间复杂度为O(n),空间复杂度为O(1)。
在这里插入图片描述

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {
    /**
     *
     * @param head ListNode类
     * @param m int整型
     * @param n int整型
     * @return ListNode类
     */
    public ListNode reverseBetween (ListNode head, int m, int n) {
        // write code here
        ListNode result = new ListNode(-1);
        result.next = head;

        ListNode pre = result;
        //先找到m-1位置
        for (int i = 0; i < m - 1; i++) {
            pre = pre.next;
        }
        ListNode temp = null;
        ListNode cur = pre.next;
        for (int i = 0; i < n - m; i++) {
            temp =  cur.next;
            cur.next = temp.next;
            temp.next = pre.next;
            pre.next = temp;
        }
        return result.next;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值