题解 | #链表内指定区间反转#
链表内指定区间反转
http://www.nowcoder.com/practice/b58434e200a648c589ca2063f1faf58c
思路看起来很好理解的
public ListNode reverseBetween (ListNode head, int m, int n) {
// 写虚拟头节点是为了找前驱,防止从第一个开始他没有前驱。
ListNode dummy=new ListNode(Integer.MIN_VALUE);
dummy.next=head;
ListNode cur=head;
ListNode pre=dummy;
if (head==null){
return null;
}
// 从第一个到第m个次序都正常
for (int i = 1; i <m ; i++) {
pre=cur;
cur=cur.next;
}
// m到n开始反转
for (int i = m; i <n ; i++) {
//
// 2 【3 4 5】 6反转
/*
pre 是3之前的 比如说是2,cur=3,temp=4,cur.next=temp.next
变化为 3--》6,temp.next=pre.next 2--->4
pre.next=temp pre 此时的顺序为 2---》4---》3---》5---》6
然后循环
*/
ListNode temp=cur.next;
cur.next=temp.next;
temp.next=pre.next;
pre.next=temp;
}
// 后面的次序正常就不管了
return dummy.next;
}