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.

  • 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 nodes, only nodes itself may be changed.
  • Only constant memory is allowed.

For 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

Solution (recursive):

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseKGroup(ListNode* head, int k) {
        int length = 0;
        ListNode *p = head, *p2;
        while ( p != NULL ) {
            p = p->next;
            length += 1;
        }
        if ( length < k or k <= 1) return head;
        p = head;
        p2 = head->next;
        for ( int i = 0; i <= k-2; i++ ) {
            ListNode *tmpp = p2->next;
            p2->next = p;
            p = p2;
            p2 = tmpp;
        }
        ListNode *newp = reverseKGroup(p2, k);
        head->next = newp;
        return p;
    }
};

Non-recursive solution

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    int len(ListNode* head) {
        ListNode* p = head;
        int i = 0;
        while ( p != NULL ) {
            i += 1;
            p = p->next;
        }
        return i;
    }
    ListNode* reverseKGroup(ListNode* head, int k) {
        int n = len(head);
        if ( k <= 1 or k > n ) return head;
        n /= k;
        ListNode* dummy = new ListNode(0);
        dummy->next = head;
        ListNode* tail = dummy, *prev, *p, *tmp, *next;
        prev = head;
        p = head->next;
        for ( int i = 0; i < n; i++ ) {
            tmp = prev;
            for ( int j = 0; j < k; j++ ) {
                if ( p == NULL ) next = NULL;
                else next = p->next;
                if ( j != k-1 ) p->next = prev;
                else {
                    tail->next = prev;
                    tmp->next = NULL;
                    tail = tmp;
                }
                prev = p;
                p = next;
            }
        }
        tail->next = prev;
        return dummy->next;
    }
};

results matching ""

    No results matching ""