LeetCode-in-All

25. Reverse Nodes in k-Group

Hard

Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.

k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is.

You may not alter the values in the list’s nodes, only nodes themselves may be changed.

Example 1:

Input: head = [1,2,3,4,5], k = 2

Output: [2,1,4,3,5]

Example 2:

Input: head = [1,2,3,4,5], k = 3

Output: [3,2,1,4,5]

Example 3:

Input: head = [1,2,3,4,5], k = 1

Output: [1,2,3,4,5]

Example 4:

Input: head = [1], k = 1

Output: [1]

Constraints:

Follow-up: Can you solve the problem in O(1) extra memory space?

Solution

#include <stdio.h>
#include <stdlib.h>

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
// Function to create a new ListNode
struct ListNode* createNode(int val) {
    struct ListNode* node = (struct ListNode*)malloc(sizeof(struct ListNode));
    node->val = val;
    node->next = NULL;
    return node;
}

// Function to reverse nodes in groups of k
struct ListNode* reverseKGroup(struct ListNode* head, int k) {
    if (head == NULL || head->next == NULL || k == 1) {
        return head;
    }

    // Check if there are at least k nodes remaining
    struct ListNode* len = head;
    int j = 0;
    while (j < k) {
        if (len == NULL) {
            return head;
        }
        len = len->next;
        j++;
    }

    // Reverse the first k nodes
    struct ListNode* curr = head;
    struct ListNode* prev = NULL;
    struct ListNode* next = NULL;
    int i = 0;
    while (i < k) {
        next = curr->next;
        curr->next = prev;
        prev = curr;
        curr = next;
        i++;
    }

    // Recursively call for the next group of k nodes
    head->next = reverseKGroup(next, k);
    return prev;
}