My Java solution


  • 0
    S
    public ListNode reverseKGroup(ListNode head, int k) {
            ListNode dummy = new ListNode(0);
            dummy.next=head;
            ListNode prev=dummy, cur=prev.next;
            int count=1;
            while(cur!=null){
                if(count==k){
                    count=1;
                    prev=reverse(prev,cur);
                    cur=prev.next;
                }
                else{
                    cur=cur.next;
                    count++;
                }
            }
            return dummy.next;
        }
        
        private ListNode reverse(ListNode start, ListNode end){
            ListNode prev=start.next, cur=prev.next;
            while(start.next!=end){
                prev.next=cur.next;
                cur.next=start.next;
                start.next=cur;
                cur=prev.next;
            }
            return prev;
        }
    

Log in to reply
 

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