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.
思路:先找到第m-1个节点,然后反转m到n的,最后拼接起来就行了。
/**
* 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) {
if(head.next==null||head==null||m==n) return head;
ListNode dump=new ListNode(0);
dump.next=head;
ListNode pre=dump;
for(int i=0;i<m-1;i++){
pre=pre.next;
}
ListNode curr=pre.next,save=pre.next,p=null;
for(int i=0;i<=n-m;i++){
ListNode nex=curr.next;
curr.next=p;
p=curr;
curr=nex;
}
save.next=curr;
pre.next=p;
return dump.next;
}
}