Java Solution for Reverse Nodes in k-Group


  • 0
    V

    /**

    • Definition for singly-linked list.

    • public class ListNode {

    • int val;
      
    • ListNode next;
      
    • ListNode(int x) { val = x; }
      
    • }
      */
      class Solution
      {
      boolean hasKElements(ListNode head,int k)
      {
      ListNode ptr= head;
      int check=0;

       while((ptr!=null)&&(check<k))
       {
           check++; 
           ptr = ptr.next;      
       }
       
       if(check <k)
       {
           return false;
       }
       else
       {
           return true;
       }
      

      }

      public ListNode reverseKGroup(ListNode head, int k)
      {

       if(head==null)
       {
           return null;
       }
       else
       {
           ListNode tail=null,reverseList=null,temp;
           tail = new ListNode(head.val);
           temp = tail;
      
            if(hasKElements(head,k))
            {
            
              for(int i=0; i<k;i++)
              {
                if(temp==null)
                {
                temp =new ListNode(head.val);
                }
                temp.next =reverseList;
                reverseList = temp; 
                temp =null;
                head = head.next;
    
               } 
        
                tail.next = reverseKGroup(head,k);  
                return reverseList;
    
            }
             else
            {
            return head;
            }
            
        }
        
        
    
    }
    

    }


Log in to reply
 

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