jason89521 / leetcode_note

0 stars 0 forks source link

25. Reverse Nodes in k-Group #6

Open jason89521 opened 2 months ago

jason89521 commented 2 months ago

Practice Dates

Description

Link: https://leetcode.com/problems/reverse-nodes-in-k-group/description/

Solution

Find a group of k elements. If there are k elements, reverse the group and link the last element to the rest of the list. Repeat this process until there are no longer k elements present.

/**
 * 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* reverseKGroup(ListNode* head, int k) {
        if (k == 1) return head;
        ListNode* result = nullptr;
        ListNode* cursor = head;
        ListNode* oldCursor = nullptr;
        while (cursor != nullptr) {
            ListNode* tail = cursor;
            for (int i = 0; i < k - 1; i++) {
                tail = tail->next;
                if (tail == nullptr) {
                    return result;
                }
            }

            ListNode* nextCursor = tail->next;
            ListNode* originalCursor = cursor;
            ListNode* prev = nullptr;
            while (cursor != nextCursor) {
                ListNode* next = cursor->next;
                cursor->next = prev;
                prev = cursor;
                cursor = next;
            }

            originalCursor->next = nextCursor;

            if (result == nullptr) {
                result = prev;
                oldCursor = originalCursor;
            } else {
                oldCursor->next = prev;
                oldCursor = originalCursor;
            }
        }

        return result;
    }
};

Performance

Time complexity:

jason89521 commented 2 months ago

There is another implementation that using a dummy node pointing to the head. Should use this approach next time trying to resolve this problem.