Share my Java recursive solution, easy to understand


  • 0
    S
    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public ListNode reverseKGroup(ListNode head, int k) {
            ListNode fast = head;
            int i = 1;
            while (i++ < k && fast != null) fast = fast.next;
            if (fast == null) return head;
            ListNode cur = reverseKGroup(fast.next, k);
            fast.next = null;
            ListNode rev = reverse(head, cur);
            return rev;
        }
        
        public ListNode reverse(ListNode head, ListNode cur) {
            while (head != null) {
                ListNode next = head.next;
                head.next = cur;
                cur = head;
                head = next;
            }
            return cur;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.