public ListNode reverseBetween (ListNode head, int m, int n) { // write code here int i = 1; ListNode res = head; ListNode pre = new ListNode(1); pre.next = head; ListNode flag=new ListNode(0); while(head!=null){ if(i>=m && i<=n){ if(i==m){ //保存反转后的最后一个节点 便于后面链接 flag = pre.next; } ListNode temp = head.next; head.next = pre.next; pre.next = head; head = temp; if(i==n){ //将反转后的最后一个节点连接起来 flag.next = head; } }else if(i>n){ head = head.next; }else{ head = head.next; pre = pre.next; } i++; //head = head.next; //pre = pre.next; } //**注意可能从第一个节点就开始反转,所以结果也不一样** return m==1?pre.next:res; }