题解 | #链表内指定区间反转#
链表内指定区间反转
http://www.nowcoder.com/practice/b58434e200a648c589ca2063f1faf58c
/*
* 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
if(m == n){
return head;
}
ListNode newHead = new ListNode(-1);
newHead.next = head;
ListNode pre = newHead;
ListNode cur = head;
for(int i = 1;i < m; i++){
pre = cur;
cur = cur.next;
}
for(int i = m; i < n;i ++){
ListNode node = cur.next;
cur.next = node.next; //2->4
node.next = pre.next; //3->2
pre.next = node; //1->3
}
return newHead.next;
}
}