BM2 链表内指定区间反转
代码有点长,但是我比较喜欢这种做法。
注意的点是如果第一个参与了反转,那么返回的就是区间反转之后的头结点,而不是原始头结点。
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* public ListNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
public ListNode reverse(ListNode head,ListNode tail){
if(head == null || head == tail){
return head;
}
ListNode reverseHead = reverse(head.next,tail);
head.next.next = head;
head.next = null;
return reverseHead;
}
public ListNode reverseBetween (ListNode head, int m, int n) {
if(m == n) return head;
ListNode first = head,last = head;
ListNode pre = null;
for(int i=1;i<m;i++){
pre = first;
first = first.next;
}
for(int i=1;i<n;i++){
last = last.next;
}
ListNode lastNext = last.next;
reverse(first,last);
if(pre != null){
pre.next = last;
}
first.next = lastNext;
if(m==1) return last;
return head;
}
}