题解 | #链表内指定区间反转#
链表内指定区间反转
https://www.nowcoder.com/practice/b58434e200a648c589ca2063f1faf58c
import java.util.*; /* * public class ListNode { * int val; * ListNode next = null; * public ListNode(int val) { * this.val = val; * } * } */ //大的思路是把需要遍历的链表从当前链表断开,然后对反转链表进行头插法,再接回断开的链表就ok了 //首先搞个虚拟头节点dummyNode,定义指针一个pre到待反转链表的前一个节点,再搞一个指针到反转链表的最后一个节点 //定义两个指针截取链表leftnode和cur,最后断开,再对截取链表反转,最后接回 public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 * @param m int整型 * @param n int整型 * @return ListNode类 */ public ListNode reverseBetween (ListNode head, int m, int n) { // write code here if(head==null){ return null; } ListNode dummyNode=new ListNode(-1); dummyNode.next=head; ListNode pre=dummyNode; //走到待反转的前一个节点, for(int i=0;i<m-1;i++){ pre=pre.next; } //走到待反转的最后一个节点 ListNode rightNode=pre; for(int i=0;i<n-m+1;i++){ rightNode=rightNode.next; } //开始截取反转链表 ListNode leftnode =pre.next; ListNode cur=rightNode.next; //断开 pre.next=null; rightNode.next=null; retrans(leftnode); pre.next=rightNode; leftnode.next=cur; return dummyNode.next; } public void retrans(ListNode head){ ListNode pre=null; ListNode cur=head; while(cur!=null){ ListNode curnext=cur.next; cur.next=pre; pre=cur; cur=curnext; } } }