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

struct ListNode 
{
    int val;
    ListNode *next;
    ListNode(int x =0) : val(x), next(NULL) {}
};

void ReverseList(ListNode ** head, ListNode* tail)
{
   ListNode * p = *head;
   ListNode * q = tail;
   ListNode * n;

   //make next pointer of node point to previous node
   while( p != tail)
   {
      n = p->next;
      p->next = q;
      q = p;
      p = n;
    }

   //make head pointer to new start
   *head = q;
}

ListNode *ReverseNodesink_Group(ListNode *head, k) 
{
    ListNode ** h = &head;
    ListNode * t = head;
    ListNode * n = head;
    
    while(1)
    {
        int count = k;
        while(--count > 0 && t != NULL)
        {
            t = t->next;
        }

        if (t == NULL) break;
        
        //after reverse the list, the head node would be the last node,
        //and pointer to the next segment, we need to reserve this node 
        //to find next start point
        n = *h;
        
        ReverseList(h, t->next);
        
        //begin next reverse
        h = &n->next;
        t= n->next;
    }

    return head;    
}
View Program Text


Test Status