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,n的链表逆序
public class Solution {
public void reverse(ListNode pre,ListNode next){
ListNode last = pre.next;
ListNode cur = last.next;
while(cur!= next){
last.next = cur.next;
cur.next = pre.next;
pre.next = cur;
cur = last.next;
}
}
public ListNode reverseBetween(ListNode head, int m, int n) {
ListNode res = new ListNode(-1);
res.next = head;
int index = 1;
ListNode tmp = res;
while(tmp!=null&&index<m){
tmp = tmp.next;
index++;
}
ListNode pre = tmp;
while(tmp!=null&&index<n){
tmp = tmp.next;
index++;
}
tmp=tmp.next;
ListNode next=tmp.next;
reverse(pre, next);
return res.next;
}
}