image.png

    1. /**
    2. * Definition for singly-linked list.
    3. * struct ListNode {
    4. * int val;
    5. * ListNode *next;
    6. * ListNode() : val(0), next(nullptr) {}
    7. * ListNode(int x) : val(x), next(nullptr) {}
    8. * ListNode(int x, ListNode *next) : val(x), next(next) {}
    9. * };
    10. */
    11. class Solution {
    12. public:
    13. ListNode* reverseBetween(ListNode* head, int left, int right) {
    14. ListNode *dummy =new ListNode(-1);
    15. dummy->next = head;
    16. ListNode *prev = dummy;
    17. for(int i = 0; i < left - 1; i ++) prev = prev->next;
    18. ListNode *l = prev->next;
    19. ListNode *r = l->next;
    20. for(int i = 0; i < (right - left); i ++){
    21. ListNode *next = r->next;
    22. r->next = l;
    23. l = r, r = next;
    24. }
    25. prev->next->next = r;
    26. prev->next = l;
    27. return dummy->next;
    28. }
    29. };