将一个链表 m 位置到n 位置之间的区间反转,要求时间复杂度 O(n),空间复杂度 O(1)。
反转链表能想到头插法,这道题也是类似的思路,和链表相关的题目需要注意细节,尤其是头插法的具体实现,主要分为3步和几个变量:首先是记录当前位置的cur指针,然后是记录反转区间之前,在整个循环中一直不动的pre指针,最后是cur之后的next指针,每次头插法的步骤如下:首先记录pre.next,将cur指针的next指向cur.next.next,将pre指针的next指向cur.next,最后将pre.next的next指向最初pre的下一个节点。
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 cur = head;
ListNode dummy = new ListNode(-1);
ListNode pre = dummy;
dummy.next = head;
for(int i = 1;i < m;i++){
pre = cur;
cur = cur.next; //p移到反转开始位置
}
for(int i = m-1;i < n-1;i++){
ListNode next = cur.next;
cur.next = next.next;
ListNode temp = pre.next;
pre.next = next;
next.next = temp;
}
return dummy.next;
}
}