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;
    }
};

Submission 211204

/**
 * 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 left, int right) {
        ListNode *dummy = new ListNode(0, head);
        ListNode *begin = dummy, *end = dummy;

        for(int i = 1; begin != nullptr && i != left; ++i, begin = begin->next);
        for(int i = 0; end != nullptr && i != right + 1; ++i, end = end->next);
        
        ListNode *nextNode = end;
        for(ListNode *node = begin->next; node != end; ) {
            ListNode *tmp = node->next;
            node->next = nextNode;
            nextNode = node;
            node = tmp;
        }
        begin->next = nextNode;

        return dummy->next;
    }
};

Leave a Reply

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