题目如下:
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.
实现
public class Solution92 {
public ListNode reverseBetween(ListNode head, int m, int n) {
//创建一个虚拟节点
ListNode curr = new ListNode(0);
curr.next=head;
//翻转次数
int k= n-m;
//寻找翻转位置
int j=m;
//寻找翻转位置--curr最终的位置为要翻转的左邻居
while(j>1){
curr = curr.next;
j--;
}
//当前操作节点 也就是翻转最左侧节点 其next指针一直在变 但其内容一直不变
ListNode reve =curr.next;
while(k>0){
//当前节点的右邻居
ListNode temp = reve.next;
//将当前节点的下一个节点指向右邻居的下一个节点
reve.next=reve.next.next;
//将右邻居的下一个节点指向curr --即curr为开始节点的左邻居
temp.next=curr.next;
//将起始节点的下一个节点指向右邻居
curr.next=temp;
k--;
}
if(m==1)
head=curr.next;
return head;
}