25. Reverse Nodes in k-Group

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
52
53
54
55
56
57
58
59
60
61
62
63
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
  
 /**
  * use three pointer, a, b, mid.
  * iterator k times
  * every time, a0 a->b => a0<-a b 
  
  * pre -> 1 -> 2 -> 3 -> 4 -> 5 -> 6...
  *   |    |    |
  *   a0   a    b
  * pre <- 1    2 -> 3 -> 4 -> 5 -> 6...
  *        |    |    |
  *       a0    a    b
  * pre <- 1 <- 2    3 -> 4 -> 5 -> 6...
  *        |    |    |    |
  *     head   a0    a    b
  * at the end, a0 is the new head, and the original head points to the sub-list(reverse the sub-list)
  * Then recursion the whole process
  
  * Corner Case:
  * 1 When a is the last node in the list, b = NULL, then b->next could cause run time error
  * 2 if k == 1, return
  * 3 if k > list length ,return
  * 4 if head == NULL or head->next == NULL, return
  
  
  */
class Solution {
public:
    ListNode* reverseKGroup(ListNode* head, int k) {
        int len = k;
        ListNode * pnode = head;
         
        while(len > 0 && pnode!=NULL ){
            pnode=pnode->next;
            len--;
        }
        if(len != 0 ) return head;//case 3
        if(k <= 1 || head ==NULL || head->next == NULL)return head;//case 2 and case 4
         
        ListNode pre(0);
        ListNode *a0 = &pre, *a = head, *b = head->next;
        len = k;
        while(len > 0){
            a->next = a0;
            a0 = a;
            a = b;
            if(b)b = a->next;//case 1
            len--;
        }
         
        head->next = reverseKGroup(a,k);
        return head = a0;
         
    }
};




原文地址:https://www.cnblogs.com/zhxshseu/p/6282499.html