Simple solution in java


  • 0
    X
    public class Solution {
        public ListNode reverseKGroup(ListNode head, int k) {
            if(validLen(head,k)){
                ListNode newHead = head;
                int step = k;
                while(--step>0){
                    ListNode temp = head.next;
                    head.next = head.next.next;
                    temp.next = newHead;
                    newHead = temp;
                }
                head.next = reverseKGroup(head.next,k);
                return newHead;
            }
            return head;
        }
    
        private boolean validLen(ListNode head,int k){
            int len = 0;
            while(head!=null && len<k){
                len+=1;
                head=head.next;
            }
            return len==k;
        }
    }

  • 0
    F

    The problem specifies the solution must use constant memory; yours uses O(n) memory since you recurse to a depth of n/k.


Log in to reply
 

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