import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head ListNode类
* @param m int整型
* @param n int整型
* @return ListNode类
*/
public ListNode reverseBetween (ListNode head, int m, int n) {
//有0或1个结点或者1个节点原地翻转
if(head == null || head.next == null || m==n){
return head;
}
//设置虚拟头节点
ListNode dummyNode = new ListNode(-1);
dummyNode.next =head;
ListNode pre = dummyNode;
for(int i=0;i<m-1;i++){
pre = pre.next;
}
//原地翻转
//cur和per指向的部分是永远不变的,只变curNext
ListNode cur = pre.next;
ListNode Cur_next ;
for(int i=0;i<n-m;i++){
Cur_next = cur.next;
cur.next = Cur_next.next;
Cur_next .next = pre.next;
pre.next = Cur_next ;
}
return dummyNode.next;
}
}
cur
指向的是翻转部分的头节点(即,翻转后的尾节点),每次移动是将cur
的下一个节点移动到翻转部分头节点的位置(也就是per
的下一个节点)
题解
大佬的思路太牛了!这个原地翻转想了半天才懂