[leetcode_25] Reverse Nodes in k-Group

Singly linked list — reverse every k nodes. If the remaining length is less than k, do not reverse.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class Solution {
public:
    int len;
    ListNode *reverseKGroup(ListNode *head, int k) {
        len = getLength(head);
        if(len < k || head == NULL || k <= 1) {
            return head;
        }
        ListNode ** tmp = new ListNode *[2];
        tmp = reverseKStep(head,k);
        len -= k;
        head = tmp[0];
        
        ListNode * beforebackup = tmp[1];
        while(len >= k) {
            tmp = reverseKStep(beforebackup->next,k);
            len -= k;
            beforebackup->next = tmp[0];
            beforebackup = tmp[1];
        }
        return head;
    }

private:
    // Returns two pointers: the first is the head, the second is the last node
    ListNode **reverseKStep(ListNode *before,int k) {
        ListNode * beforebackup = before;
        ListNode * now = before->next;
        int count = 1;
        while(now != NULL && count < k) {
            count++;
            ListNode * next = now->next;
            now->next = before;
            before = now;
            now = next;
        }
        beforebackup->next = now;
        ListNode ** ans = new ListNode *[2];
        ans[0] = before;
        ans[1] = beforebackup;
        return ans;
    }
    int getLength(ListNode *head) {
        int lentmp = 0;
        while(head != NULL) {
            head = head->next;
            lentmp++;
        }
        return lentmp;
    }
};