Easy and Simple O(n) Java Solution


  • 0
    D
    class Solution
    {
        public ListNode reverseKGroup(ListNode head, int k)
        {
        	ListNode temp = head;
        	
        	ListNode t = head;
            ListNode res = t;
            
            while(t!=null)
            {
            	int a[] = new int[k];
            	int i = 0;
            	for(i=0; i<k && t!=null; i++)
            	{
            		a[i] = t.val;
            		t = t.next;
            	}
            	if(t==null && i!=k)
            	{
            		t = temp;
            		for(int j=0; j<i; j++)
            		{
            			t.val= a[j];
            			t = t.next;
            			temp = temp.next;
            		}
            	}
            	else
            	{
            		t = temp;
            		for(int j=k-1; j>=0; j--)
            		{
            			t.val = a[j];
            			t = t.next;
            			temp = temp.next;
            		}
            	}
            	
            }
            return res;
        }
    }
    

Log in to reply
 

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