Skip to content
Rain Hu's Workspace
Go back

[LeetCode] 25. Reverse Nodes in k-Group

Rain Hu

25. Reverse Nodes in k-Group


一、題目

Given the head of a linked list, reverse the nodes of the list k at a time, and return the 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:
reverse_ex1

Example 2: reverse_ex2

Constraints:


二、分析

三、解題

1. Recursion

ListNode* reverseKGroup(ListNode* head, int k) {
    int cnt = k;
    ListNode* last = head;
    while (cnt && last) {
        last = last->next;
        cnt--;
    }
    if (cnt == 0) {
        last = reverseKGroup(last, k);
        ListNode* prev = nullptr;
        ListNode* curr = head;
        ListNode* next = nullptr;
        cnt = k;
        while (cnt--) {
            next = curr->next;
            curr->next = prev;
            prev = curr;
            curr = next;
        }
        head->next = last;
        head = prev;
    }
    return head;
}

回目錄 Catalog


Share this post on:

Previous
[LeetCode] 841. Keys and Rooms
Next
[LeetCode] 24. Swap Nodes in Pairs