class ListNode {
    int val;
    ListNode next;
    ListNode(int x) { val = x; }
}

public class Solution {
    public ListNode reverseBetween(ListNode head, int m, int n) {
        if (head == null || m == n) {
            return head;
        }
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        head = dummy;
        // 找到m位置的前一个节点
        for (int i = 1; i < m; i++) {
            head = head.next;
        }
        // 翻转区间[m, n]中的链表
        ListNode prev = null, curr = head.next;
        for (int i = m; i <= n; i++) {
            ListNode next = curr.next;
            curr.next = prev;
            prev = curr;
            curr = next;
        }
        // 将翻转后的链表与原链表连接起来
        head.next.next = curr;
        head.next = prev;
        return dummy.next;
    }
}
将一个节点数为size链表m位置到n位置之间的区间反转要求时间复杂度为On空间复杂度为O1java实现

原文地址: https://www.cveoy.top/t/topic/bnqr 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录