Short recursive java solution


  • 5
    A
    public class Solution {
           
       public  ListNode reverse(ListNode head, ListNode end){
    	       if(head==null || head.next==null || head==end || head.next==end) return head;
    	       ListNode sec = head.next;
    	       ListNode rem = reverse(sec,end);
    	       sec.next =head; head.next=null;
    	       return rem;
    	   }
    	    public  ListNode reverseKGroup(ListNode head, int k) {
    	        ListNode curr = head; int count = 0;
    	        while (curr != null && count != k) {
    	            curr = curr.next;count++;
    	        }
    	        if (count == k) {
    	            ListNode temp = reverseKGroup(curr, k);
    	            ListNode t = reverse(head,curr);
    	            head.next = temp;
    	            return t;
    	        }
    	        return head;
    	    }
    }

  • 0
    D

    How come this is O(1) space? This is not tailing recursion.


Log in to reply
 

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