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.
思路:只要会了reverse k-group,反转链表再也不用愁了呢!
1 class Solution { 2 public: 3 ListNode* reverseBetween(ListNode* head, int m, int n) { 4 if (head == NULL || m == n) return head; 5 ListNode prenode(-1); 6 prenode.next = head; 7 ListNode *pre = &prenode, *cur, *nex; 8 int count = m - 1; 9 while (count && (pre = pre->next)) 10 count--; 11 cur = pre->next; 12 nex = cur->next; 13 for (int i = 1; i < n - m + 1; i++) 14 { 15 cur->next = nex->next; 16 nex->next = pre->next; 17 pre->next = nex; 18 nex = cur->next; 19 } 20 return prenode.next; 21 } 22 };