Short and clean recursive Java solution(Reuse code from reverse linked list)


  • 0
    S
    public class Solution {
        public ListNode reverseList(ListNode head) {
          if (head == null || head.next == null) return head;
          
          ListNode reversed = reverseList(head.next);
          head.next.next = head;
          head.next = null;
          
          return reversed;
        }
        
        public ListNode reverseKGroup(ListNode head, int k) {
          if (head == null || head.next == null) return head;
          
          ListNode runner = head;
          int temp = 1;
          while (temp < k && runner != null) {
            runner = runner.next;
            temp++;
          }
          
          if (temp == k && runner != null) {
            ListNode nextNode = runner.next;
            runner.next = null;
            ListNode reversed = reverseList(head);
            head.next = reverseKGroup(nextNode, k);
            return reversed;
          }
          return head;
        }
    }

Log in to reply
 

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