Straightforward Java Solution with comments

  • 0

    The idea is as below:
    m = 2, n = 4
    dummy -> a -> b -> c -> d -> e
    dummy -> a -> c -> b -> d -> e
    dummy -> a -> d -> c -> b -> e

    prev is the node ahead of the reverse section, its next is the beginning of the reverse section. In the example above, prev always points to Node a.

    curr is the beginning of the reverse section and after the reverse, it occurs at the end of the section. In the example above, curr always points to Node b.

    next is the next ListNode should be put at the head of the reverse section. It should be the next of curr. In the example above, next is the next node of Node b.

    public ListNode reverseBetween(ListNode head, int m, int n) {      
            ListNode dummy = new ListNode(0);
   = head;
            int count = 0; // count is representing the position of prev
            ListNode prev = dummy;
            while(count < m - 1){
                prev =;
            ListNode curr =;
            ListNode next =;
            while(count < n - 1){
       = next;
                next =;

Log in to reply

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