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 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode* reverseBetween(ListNode* head, int m, int n) { 12 if (head == NULL) return NULL; 13 14 ListNode** pre = &head; 15 16 for (int i = 0; i < m - 1; i++) 17 pre = &((*pre)->next); 18 19 n -= m; 20 ListNode* start = *pre; 21 while (n--) { 22 ListNode* p = start->next; 23 start->next = p->next; 24 p->next = *pre; 25 (*pre) = p; 26 } 27 28 return head; 29 } 30 };