/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode reverseBetween(ListNode head, int m, int n) { if (head == null || head.next == null) { return head; } ListNode newHead = new ListNode(0); newHead.next = head; ListNode pre = newHead; int count = 1; while (pre != null && count != m) { pre = pre.next; count++; } ListNode leftNode = pre.next; pre.next = null; ListNode temp=null; count--; while(leftNode!=null && count < n) { count++; temp = leftNode; leftNode = leftNode.next; temp.next = pre.next; pre.next = temp; } while(pre.next!=null) { pre = pre.next; } pre.next = leftNode; return newHead.next; } }