Posted on

Description

Submission

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* reverseBetween(ListNode* head, int m, int n) {
        int i = 0;
        ListNode *dummyHead = new ListNode(-1);
        ListNode *reversedList = nullptr, *tail = nullptr;
        ListNode *ret = new ListNode(-1);
        ListNode *ptr =  ret;
        dummyHead->next = head;
        for(ListNode *node = dummyHead; node != nullptr; ++i) {
            ListNode* cur = node;
            node = node->next;
            if(i >= m && i <= n) {
                cur->next = reversedList;
                if(reversedList == nullptr) tail = cur;
                reversedList = cur;
            } else if(reversedList != nullptr) {
                ptr->next = reversedList;
                reversedList = nullptr;
                ptr = tail;
                ptr->next = cur;
                ptr = ptr->next;
            } else if(cur != dummyHead){
                ptr->next = cur;
                ptr = ptr->next;
            }
        }

        if(i == n + 1) {
            ptr->next = reversedList;
        }

        return ret->next;
    }
};

Leave a Reply

Your email address will not be published. Required fields are marked *