链表指定区间反转
链表内指定区间反转
https://www.nowcoder.com/practice/b58434e200a648c589ca2063f1faf58c?tpId=117&tags=&title=&diffculty=0&judgeStatus=0&rp=1&tab=answerKey
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; }