Accepted Java solution solved through recursion.


  • 1
    V

    I have used recursion and solved it. Here is my code

    public class Solution {
    private static ListNode s;
    private static ListNode start;
    private void reverse(ListNode current,int n){
    	if(n==0)
    		return;
    	n--;
    	reverse(current.next,n);
    	if(s==null){
    		ListNode temp = current.next;
    		current.next = temp.next;
    		temp.next = start;
    		start = temp;
    		s = start;
    		
    	} else {
    		ListNode temp = current.next;
    		current.next = temp.next;
    		temp.next = s.next;
    		s.next = temp;
    		s = s.next;
    	}
    	
    }
    public ListNode reverseBetween(ListNode head, int m, int n) {
        start = head;
        if(m==n)
    		return start;
    	ListNode current = head;
    	int i = 1;
    	ListNode temp = null;
    	while (i < m) {
    
    		temp = current;
    		current = current.next;
    		i++;
    
    	}
    	s = temp;
    	if(temp==null)
    		reverse(head,n-m);
    	else
    		reverse(temp.next,n-m);
    	
    	return start;
        
    }
    

    }


Log in to reply
 

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