将一个节点数为size链表m位置到n位置之间的区间反转要求时间复杂度为On空间复杂度为O1java实现例如12345 m=2n=4 返回14325
public ListNode reverseBetween(ListNode head, int m, int n) {
if (head == null || head.next == null || m == n) {
return head;
}
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode prev = dummy;
for (int i = 1; i < m; i++) {
prev = prev.next;
}
ListNode curr = prev.next;
for (int i = m; i < n; i++) {
ListNode next = curr.next;
curr.next = next.next;
next.next = prev.next;
prev.next = next;
}
return dummy.next;
}
原文地址: https://www.cveoy.top/t/topic/bntZ 著作权归作者所有。请勿转载和采集!