Shortest java AC solution


  • 0
    J
        public ListNode reverseKGroup(ListNode head, int k) {
            if(k<=1)    return head;
            int len = 0;
            ListNode l = head;
            while(l!=null){
                l = l.next;
                len++;
            }
            ListNode dummy = new ListNode(1);
            dummy.next = head;
            ListNode left = dummy;
            for(int i=0;i<len/k;i++){
                ListNode right = left.next;
                for(int j=0;j<k-1;j++){
                    int temp = right.next.val;
                    right.next = right.next.next;
                    ListNode temp1 = left.next;
                    left.next = new ListNode(temp);
                    left.next.next = temp1;
                }
                left = right;
            }
            return dummy.next;
        }

Log in to reply
 

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