268ms java solution


  • 0
    Y
    public class Solution {
    public ListNode reverseBetween(ListNode head, int m, int n) {
       if(m == n) return head;
       ListNode dummy = new ListNode(0);
       dummy.next = head;
       head = dummy;
       ListNode pre = null;  //  position m-1
       ListNode post = null; //  position n+1
       ListNode first = null;
       int count = 0;
    
    
       while(count < m-1) {
           count ++;
           head = head.next;
       }
       pre = head;  // position m-1
       head = head.next;
       count++;
       first = head;  //head of list need reverse
    
       ListNode prev = null;     //reverse
       while(count < n+1){
           ListNode temp = head.next;
           head.next = prev;
           prev = head;
           head = temp;
           count++;
       }
    
    
       post = head;       //connect
       pre.next = prev;
       first.next = post;
       return dummy.next;
    }
    

    }


Log in to reply
 

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