For example:
Given 1->2->3->4->5->NULL, m = 2 and n = 4,
return 1->4->3->2->5->NULL.
Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.
用一个辅助节点helper找到m的位置,然后依次交换位置,代码如下:
/** * 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 helper = new ListNode(0); helper.next = head; head = helper; int k = n - m; while(m > 1) { head = head.next; m --; } ListNode reve = head.next; while(k > 0) { ListNode cur = reve.next; reve.next = cur.next; cur.next = head.next; head.next = cur; k --; } return helper.next; } }