/** * Definition for ListNode * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */publicclassSolution { /** * @param head: ListNode head is the head of the linked list * @param m: An integer * @param n: An integer * @return: The head of the reversed ListNode */publicListNodereverseBetween(ListNode head,int m,int n) {if (head ==null||head.next==null)return head;ListNode dummy =newListNode(0);dummy.next= head;ListNode cur = dummy;// 1. proceed to m's previous nodefor (int i =0; i < m -1; i++) {if (cur ==null) returnnull; cur =cur.next; }// 2. reverse from m to nListNode mPrev = cur;ListNode mNode =cur.next; cur =cur.next;ListNode prev =null, next;for (int i = m; i <= n; i++) {if (cur ==null) returnnull; next =cur.next;cur.next= prev; prev = cur; cur = next; }// 3. connect the listsmPrev.next= prev;mNode.next= cur;returndummy.next; }}
Notes
We have three major steps here:
We first proceed to the (m-1)-th node, which is the node before the m-th node. Then we keep track of both of them.
We reverse from m to n using the same technique used in the classical reverse linked list.
Lastly, do not forget to connect the middle part, i.e., the reversed linked list, with mPrev and cur pointer.
m =2, n =4; mPrev mNode nstep1:1------->2------->3------->4------->5------->6 mPrev mNode prev curstep2:12<-------3<-------45------->6 mPrev prev mNode curstep3:1------->4------->3------->2------->5------->6