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 {
    // dummy head and pass-the-end pointer
    ListNode* reverseRange(ListNode* dummy, ListNode* end) {
        ListNode *nextNode = end;
        ListNode *ret = dummy->next;
        
        for(ListNode *cur = dummy->next; cur != end;) {
            ListNode *tmp = cur->next;
            cur->next = nextNode;
            nextNode = cur;
            cur = tmp;
        }
        dummy->next = nextNode;

        return ret;
    }
public:
    ListNode* reverseEvenLengthGroups(ListNode* head) {
        ListNode* dummy = new ListNode(-1, head);

        ListNode* begin = dummy;
        ListNode* end = begin;
        int k = 1;  // current number
        for(; true; ++k) {
            ListNode* end = begin;
            int i = 0;
            ListNode *prevEnd = end;
            for(; end != nullptr && i < k + 1; ++i) {
                prevEnd = end;
                end = end->next;
            }

            if(i % 2 == 1) {
                begin = reverseRange(begin, end);
                if(end == nullptr) break;
            } else {
                begin = prevEnd;
            }
            if(i != k+1) break;
        }

        return dummy->next;
    }
};

Leave a Reply

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