Reverse a linked list from position m to n. Do it in one-pass.
Note: 1 ≤ m ≤ n ≤ length of list.
Input: 1->2->3->4->5->NULL, m = 2, n = 4 Output: 1->4->3->2->5->NULL
翻转指定范围内的节点。
解决:用一个i记录当前是第几号节点。
1 class Solution { 2 public: 3 ListNode* reverseBetween(ListNode* head, int m, int n) { 4 int i = 1; 5 ListNode* myhead = new ListNode(0); 6 myhead->next = head; 7 ListNode* pre = myhead; 8 ListNode* curr = myhead->next; 9 while (curr->next) { 10 if (i < m || i >= n) { 11 pre = pre->next; 12 curr = curr->next; 13 ++i; 14 } 15 else { 16 ListNode* temp = pre->next; 17 pre->next = curr->next; 18 curr->next = curr->next->next; 19 pre->next->next = temp; 20 ++i; 21 } 22 } 23 ListNode* temp = myhead->next; 24 delete myhead; 25 return temp; 26 } 27 };