原题链接在这里:https://leetcode.com/problems/reverse-linked-list-ii/
本题是Reverse Linked List的拓展。
基本思路和Reverse Linked List的Method 2 相似 扩展的地方在于本题限定了reverse的范围。
需先找到reverse范围的前一个点; 翻转时while loop走一次,翻转一个点,所以用一个计数器i 来限定接下来翻转的次数知道 i<n-1.
翻转完得到的的cur是翻转后的表头,把它连载mark的后面即可。
Note: 1. 再找mark时有corner case,e.g. [2,5],1,2. mark应该是2前面一个点,所以需要加一个dunmy head. i 从0开始计数。
2. 当m==length时,mark.next == null 需单独讨论,否则下面直接用mark.next会出错。
3. 返回的应该是dunmy.next.
AC Java:
/**
* Definition for singly-linked list.
* public 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 || head.next == null){
return head;
}
ListNode dunmy = new ListNode(0);
dunmy.next = head;
ListNode mark = dunmy;
int i = 0;
while(i < m-1){
mark = mark.next;
i++;
}
if(mark.next == null){
return dunmy.next;
}
ListNode cur = mark.next;
ListNode tail = mark.next;
ListNode pre;
ListNode temp;
while(tail.next != null && i < n-1){
pre = cur;
cur = tail.next;
temp = cur.next;
cur.next = pre;
tail.next = temp;
i++;
}
mark.next = cur;
return dunmy.next;
}
}