Easy to understand Java 0ms solution


  • 0
    L

    Notice that in second for loop we need execute (n-m+1) times, then link the head and tail node of the sub-list we reversed with two (m-1) and (n+1) nodes.

    public class Solution {
        public ListNode reverseBetween(ListNode head, int m, int n) {
            if(m == n) return head;
            ListNode fake = new ListNode(0);
            ListNode p = fake;
            fake.next = head;
            for(int i = 0; i < (m-1); i++) p = p.next;
            ListNode prev = p;
            ListNode next = null;
            ListNode bound = prev;
            p = p.next;
            for(int i = m; i < (n+1); i++) {
                next = p.next;
                p.next = prev;
                prev = p;
                p = next;
            }
            bound.next.next = next;
            bound.next = prev;
            return fake.next;
        }
    }
    

Log in to reply
 

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