Well, since the head pointer may also is modified, we create a that new_head points to it to facilitate the reverse process.
For the example list 1 -> 2 -> 3 -> 4 -> 5 in the problem statement, it'll become 0 -> 1 -> 2 -> 3 -> 4 -> 5 (we init to be new_head -> val 0 ). We set a pointer to pre and new_head another to cur head . Then we insert after for times if the current node have at cur -> next pre k - 1 cur least k nodes after it (including itself). After reversing one k -group, we update to IS and to is to pre cur reverse the cur pre -> next next k -group.
The code is as follows.
1 classSolution {2 Public: 3listnode* Reversekgroup (listnode* head,intk) {4 if(!hasknodes (head, K))returnhead;5listnode* New_head =NewListNode (0);6New_head-Next =head;7listnode* pre =New_head;8listnode* cur =head;9 while(Hasknodes (cur, k)) {Ten for(inti =0; I < K-1; i++) { Onelistnode* temp = PreNext; APre, next = curNext; -Cur next = cur, nextNext; -Pre-Next Next =temp; the } -Pre =cur; -Cur = PreNext; - } + returnNew_headNext; - } + Private: A BOOLHasknodes (listnode* node,intk) { at intCNT =0; - while(node) { -cnt++; - if(CNT >= k)return true; -node = nodeNext; - } in return false; - } to};
[Leetcode] Reverse Nodes in K-group