Reverse a linked list from position m to n. Do it in one-pass.
Note: 1 ≤ m ≤ n ≤ length of list.
Example:
Input: 1->2->3->4->5->NULL, m = 2, n = 4
Output: 1->4->3->2->5->NULL
思路:反转过程:2->3->4到3->2->4到4->3->2,pre为1不变,start为2保持不变,then一开始为3,每次把then放到pre后
public ListNode reverseBetween(ListNode head, int m, int n) {
if(head == null || head.next == null) return head;
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode pre = dummy;
for(int i = 0; i < m - 1; i++){
pre = pre.next;
}
ListNode start = pre.next;
ListNode then = start.next;
for(int i = 0; i < n - m; i++){
start.next = then.next;
then.next = pre.next;
pre.next = then;
then = start.next;
}
return dummy.next;
}