25. K 个一组翻转链表(递归)

class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        if(head == null || head.next == null || k == 1) return head;
        ListNode node = head;
        int m = k;
        while(m-- != 0) {
            if(node == null) return head;
            node = node.next;
        }
        ListNode pre = reverse(head,node); // 每次找到这k个进行翻转 返回值为翻转后的头
        head.next = reverseKGroup(node,k); // 当前头会被翻转指向下一次翻转k个的返回值
        return pre; 
    }
    public ListNode reverse(ListNode head, ListNode newNode) { // 根据起点终点反转一段链表
        if(head == newNode || head.next == newNode) return head;
        ListNode node = reverse(head.next,newNode);
        head.next.next = head;
        head.next = newNode; // 只有这里不同,翻转整个链表这里指向null
        return node;
    }
}
原文地址:https://www.cnblogs.com/yonezu/p/13269132.html