JAVA one pass, beat 92%


  • 0
    L

    public class ReverseLinkedListII {

    public ListNode reverseBetween(ListNode head, int m, int n) {
    
    	if(head==null||m==n)
    		return head;
    	int count=1;
    	ListNode temp=head;
    	ListNode processor=null;
    	ListNode successor=null;
    	ListNode start=null;
    	ListNode end=null;
    	ListNode xxx=null;
    	ListNode node=null;
    	ListNode head1=null;
    	boolean flag=false;
    	while(temp!=null)
    	{
    		if(count==m-1)
    			processor=temp;
    		if(count==m)
    		{	start=temp;
    			flag=true;
    		}
    		if(count==n)
    		{
    			if((m-n+1)%2==0)
    			successor=xxx;
    			else
    				successor=temp.next;
    			end=temp;
    			flag=false;
    			if(temp!=node)
    			temp.next=node;
    			
    		}
    		if(flag)
    		{	
    			xxx=temp.next.next;
    			node=temp.next;
    			if(temp!=start)
    			temp.next=head1;
    			head1=node;
    			node.next=temp;
    			if(temp==start)
    				temp.next=null;
    		}
    		if(flag)
    		{	temp=xxx;
    			count+=2;
    			if(count>n)
    			{
    				count-=2;
    				count++;
    				temp=node;
    			}
    		}
    		else
    		{	temp=temp.next;
    			count++;
    		}
    		
    		
    	}		
    		if(processor==null&&successor==null)
    			return end;
    		if(processor!=null)
    			processor.next=end;
    		if(successor!=null)
    			start.next=successor;
    		if(processor==null)
    			return end;
    	
    		return head;
    }
    

    }


Log in to reply
 

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