My Easy Understanding Solution


  • 0
    B
    public class Solution {
    public ListNode reverseBetween(ListNode head, int m, int n) {
    		final ListNode reversedList = new ListNode(-1);
    		final int notReversedIndex = m-1;
    		reversedList.next = head;
    		ListNode notReversedListFirstTail = reversedList;
    		for(int i=1;i<=notReversedIndex;i++){
    			notReversedListFirstTail = notReversedListFirstTail.next;
    		}
    		ListNode reversedListTail = notReversedListFirstTail.next;
    		ListNode nextNode = reversedListTail.next;
    		if (nextNode!=null) {
    			for(int i=m+1;i<=n;i++){
    
    				reversedListTail.next = nextNode.next;
    				nextNode.next = notReversedListFirstTail.next;
    				notReversedListFirstTail.next = nextNode;
    				nextNode = reversedListTail.next;
    			}
    		}
    		
    		return reversedList.next;
    		
    	}
    }

Log in to reply
 

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