/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode reverseBetween(ListNode head, int m, int n) { ListNode cur = head; ListNode prev = null; int i = 1; while(i < m){ prev = cur; cur = cur.next; i++; } ListNode start = cur, end = cur; while(i < n){ ListNode nex = end.next.next; end.next.next = start; start = end.next; end.next = nex; cur = nex; i++; } if(prev != null){ prev.next = start; return head; } return start; } }
Too late night now, no energy to say anything...Just pointer operation.