25. Reverse Nodes in k-Group

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.

Example:

Given this linked list: 1->2->3->4->5

For k = 2, you should return: 2->1->4->3->5

For k = 3, you should return: 3->2->1->4->5

Note:

  • Only constant extra memory is allowed.

  • You may not alter the values in the list's nodes, only nodes itself may be changed.

ListNode* reverseList(ListNode* pre, ListNode* next) {
    ListNode *last = pre->next, *cur = last->next;
    while (cur != next) {
        last->next = cur->next;
        cur->next = pre->next;
        pre->next = cur;
        cur = last->next;
    }
    return last;
}
ListNode* reverseKGroup(ListNode* head, int k) { // time: O(n * k); space: O(1)
    if (!head || k == 1) return head;
    ListNode *dummy = new ListNode(-1);
    dummy->next = head;
    ListNode *cur = head, *pre = dummy;
    int i = 0;
    while (cur) {
        ++i;
        if (i % k == 0) {
            pre = reverseList(pre, cur->next);
            cur = pre->next;
        } else {
            cur = cur->next;
        }
    }
    ListNode *res = dummy->next;
    delete dummy;
    return res;
}
ListNode* reverseKGroup(ListNode* head, int k) { // time: O(n * k); space: O(1)
    ListNode* dummy = new ListNode(-1);
    ListNode *pre = dummy, *cur = head;
    dummy->next = head;
    int count = 0;
    while (cur) {
        ++count;
        cur = cur->next;
    }
    while (count >= k) {
        cur = pre->next;
        for (int i = 1; i < k; ++i) {
            ListNode *t = cur->next;
            cur->next = t->next;
            t->next = pre->next;
            pre->next = t;
        }
        pre = cur;
        count -= k;
    }
    ListNode* res = dummy->next;
    delete dummy;
    return res;
}

Last updated

Was this helpful?