1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
|
class Solution { public: ListNode* reverseBetween(ListNode* head, int m, int n) { ListNode* dummy = new ListNode(0), *a, *b, *c; dummy->next = head; a = b = c = dummy; for (int i = 0; i < m - 1; i++) { a = a->next; b = b->next; } for (int i = 0; i < n - m + 1; i++) { b = b->next; } c = b->next; b->next = NULL; a->next = reverseList(a->next); while (a->next != NULL) { a = a->next; } a->next = c; return dummy->next; } ListNode* reverseList(ListNode* head) { if (head == NULL || head->next == NULL) return head; ListNode *temp = reverseList(head->next); head->next->next = head; head->next = NULL; return temp; } };
|