1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| class Solution { public: ListNode* reverseBetween(ListNode* head, int left, int right) { if (left == right) return head; ListNode* dummyHead = new ListNode(0, head); ListNode* prev = dummyHead; int i = 1; for (; i < left; ++i) prev = prev->next; ListNode *conn = prev, *tail = prev->next ,*curr = prev->next; while (i++ <= right) { ListNode* next = curr->next; curr->next = prev; prev = curr; curr = next; } if (conn) conn->next = prev; else dummyHead->next = prev; tail->next = curr; return dummyHead->next; } };
|