分两步:1是找到断链的地方(开始反转的第一个节点),2是反转链表。
public class Solution {
public ListNode reverseBetween (ListNode head, int m, int n) {
ListNode newh = new ListNode(0);
newh.next = head;
ListNode p = head;
ListNode pre = newh;
for(int i = 1;i<m;++i){
pre = p;
p = p.next;
}
ListNode q = p;
pre.next = null;
for(int i =m;i<n;++i){
ListNode temp = p.next;
p.next = temp.next;
temp.next = q;
q = temp;
}
pre.next = q;
return newh.next;
}
}