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 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
|
class Solution { public: ListNode* successor;
ListNode* reverseN(ListNode* head, int n) { ListNode* pre = NULL; auto cur = head; while (cur && n > 0) { auto next = cur->next; cur->next = pre; pre = cur; cur = next; n--; }
head->next = cur; return pre; }
ListNode* reverseN(ListNode* head, int n) { if (!head) return head; if (n == 1) { successor = head->next; return head; }
auto x = reverseN(head->next, n - 1); (head->next)->next = head; head->next = successor; return x; }
ListNode* reverseBetween(ListNode* head, int m, int n) { if (m == 1) { return reverseN(head, n); }
auto x = reverseBetween(head->next, m - 1, n - 1); head->next = x; return head; } };
|