Topic links: reverse list II
The meaning of problems: reversed from the position m to n list. Please use the trip to the scan is complete reversal.
Description:
. 1 ≤ m ≤ n- ≤ chain length.
Input: l-> 2-> 3-> 4-> 5-> NULL, m = 2, n- =. 4
Output: 1-> 4-> 3-> 2-> 5-> NULL
Solution: feeling is the k-th set of inverted list changed next. . Also the simpler. Go of m, then reversed from m to n. You can view links.
Code:
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 13 ListNode* ans = new ListNode(0); 14 ListNode* pre = ans; 15 ListNode* cur = head; 16 ListNode* tail = ans; 17 ans->next = head; 18 19 for(int i = 1; i < m;i++){ 20 head = head->next; 21 pre = cur; 22 cur = head; 23 } 24 25 for(int i = m;i < n;i++){ 26 tail = cur->next; 27 28 cur->next = tail->next; 29 tail->next = pre->next; 30 pre->next = tail; 31 } 32 33 return ans->next; 34 35 } 36 };