Reverse a linked list from position m to n. Do it in-place and in one-pass.
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.
1 public class Solution { 2 public ListNode reverseBetween(ListNode head, int m, int n) { 3 if(head==null || m==n) return head; 4 ListNode safe = new ListNode(-1); 5 ListNode pre = safe; 6 safe.next = head; 7 int step = n-m; 8 while(m>1){ 9 pre = pre.next;//to the previous of m_th node 10 m--; 11 } 12 ListNode cur = pre.next; 13 ListNode post = cur.next; 14 while(step>0 ){ 15 ListNode temp = post.next; 16 post.next = cur; 17 cur = post; 18 post = temp; 19 step--; 20 } 21 ListNode temp = pre.next; 22 pre.next = cur; 23 temp.next = post; 24 return safe.next; 25 } 26 }
原文:http://www.cnblogs.com/krunning/p/3552035.html