递归方法实现

使用递归能够很好的把链表分成长度为k的若干块(最后一块长度小于k),


/*
 * 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) {
        ListNode tail=head;//存住原来的老头
        for(int i=0;i<k;i++){
            if(tail==null) return head;//递归终止条件
            tail=tail.next;
        }
        ListNode newHead=reverse(head,tail);// 反转前 k 个元素
        head.next=reverseKGroup(tail,k);//老头指向下一轮的新头
        return newHead;//递归完成后 返回新头
    }
    //返回反转后的新头
    private ListNode reverse(ListNode head, ListNode tail) {
        ListNode pre=null;
        while(head!=tail){
            ListNode next= head.next;
            head.next=pre;
            pre=head;
            head=next;
        }
        return pre;
    }
}