Simple and straight forward recursive Java solution


  • 0
    S
    public class Solution {
        public ListNode reverseKGroup(ListNode head, int k) {
            ListNode ptr = head;
            //judge the length of group
            for(int i=0; i<k; i++) {
                if(ptr == null) return head;
                ptr = ptr.next;
            }
            
            ListNode fakehead = new ListNode(0);
            fakehead.next = head;
            ptr = fakehead;
            ListNode curr = ptr.next;
            //reverse the group
            for(int i=0; i<k-1; i++) {
                ListNode move = curr.next;
                curr.next = move.next;
                move.next = ptr.next;
                ptr.next = move;
            }
            
            curr.next = reverseKGroup(curr.next, k);
            
            return fakehead.next;
        }
    }

Log in to reply
 

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