# Straightforward Java Solution with comments

• 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);
int count = 0; // count is representing the position of prev
ListNode prev = dummy;
while(count < m - 1){
count++;
prev = prev.next;
}
ListNode curr = prev.next;
ListNode next = curr.next;
while(count < n - 1){
curr.next = next.next;
next.next = prev.next;
prev.next = next;
next = curr.next;
count++;
}
return dummy.next;
}
``````

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