链表第3天

78 阅读1分钟

25. K 个一组翻转链表

class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        ListNode a, b;
        a = b = head;
        for(int i = 0; i < k; i++){
            if(b == null)
                return head;
            b = b.next;
        }
        ListNode res = reverseAToB(a, b);

        a.next = reverseKGroup(b, k);
        return res;
    }

    public ListNode reverseAToB(ListNode a, ListNode b){
        ListNode pre = null, cur = a;
        
        while(cur != b){
            ListNode next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }

        return pre;
    }
}