Reverse Linked List II
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.
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public class Solution { 2 public ListNode reverseBetween(ListNode head, int m, int n) { 3 ListNode safe = new ListNode(-1); 4 safe.next = head; 5 ListNode pre = safe; 6 for(int i=1;i<m;i++){ 7 pre = pre.next; 8 } 9 ListNode cur = pre.next; 10 ListNode post = cur.next; 11 for(int i=0;i<n-m;i++){ 12 ListNode temp = post.next; 13 post.next = cur; 14 cur = post; 15 post = temp; 16 } 17 pre.next.next = post; 18 pre.next = cur; 19 return safe.next; 20 } 21 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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 }