Share my FASTEST and Simple Recursive Java solution


  • 0
    W
    public class Solution {
        public ListNode reverseKGroup(ListNode head, int k) {
            if (head == null) return null;
            if (k <= 1) return head;
            ListNode runner = head;
            int i = 1;
            while (runner != null && i < k){
                runner = runner.next;
                i++;
            }
            if (runner == null) return head;
            
            ListNode preHead = new ListNode(0);
            preHead.next = head;
            ListNode start = head.next;
            i = 1;
            while (i < k){
                ListNode tmp = preHead.next;
                preHead.next = start;
                start = start.next;
                preHead.next.next = tmp;
                i++;
            }
            
            head.next = reverseKGroup(start, k);
            return preHead.next;
        }
    }

Log in to reply
 

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