Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example:
Given 1->2->3->4->5->NULL
, m = 2 and n = 4,
return 1->4->3->2->5->NULL
.
Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.
1 class Solution { 2 public ListNode reverseBetween(ListNode head, int m, int n) { 3 if(head == null) return head; 4 ListNode fakehead = new ListNode(0); 5 fakehead.next = head; 6 ListNode pre = fakehead; 7 8 9 for (int i = 0; i < m-1;i++) pre = pre.next; 10 11 ListNode start = pre.next; 12 ListNode then = start.next; 13 14 for(int i = 0 ;i < n -m ;i++){ 15 start.next= then.next; 16 then.next = pre.next; 17 pre.next = then; 18 then=start.next; 19 } 20 return fakehead.next; 21 } 22 }