/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param head ListNode类 
     * @param k int整型 
     * @return ListNode类
     */
    public ListNode reverseKGroup (ListNode head, int k) {
        // write code here
        if(k<=0 || head == null){
            return head;
        }
        ListNode newHead = new ListNode(-1);
        //每次的头结点
        ListNode currentNode = newHead;
         
        
        while(true){
            int i = 0;
            ListNode nextPos = head;
            ListNode temp ;
            for(;i< k && head != null;i++){
                temp = head.next;
                head.next = currentNode.next;
                currentNode.next = head;
                head = temp;
            }
            if(i == k){
                //每次翻转前的第一个节点 保持翻转后连接起来
                currentNode = nextPos;
            }else{
                //后面不足k 也翻转了,需要再次翻转过来
                //head = currentNode.next 最后一组里一个节点
                for(head = currentNode.next,currentNode.next = null;head!=null;){
                    temp = head.next;
                    head.next = currentNode.next;
                    currentNode.next = head;
                    head = temp;
                    
                }
                break;
            }
            
            
            
        }
        
        return newHead.next;
    }
}