题解 | #链表内指定区间反转#
链表内指定区间反转
https://www.nowcoder.com/practice/b58434e200a648c589ca2063f1faf58c
import java.util.*; /* * public class ListNode { * int val; * ListNode next = null; * public ListNode(int val) { * this.val = val; * } * } */ 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 ListNode res = new ListNode(-1); //加个表头 res.next = head; ListNode pre = res; ListNode cur = head; //m之前是正常顺序 for(int i=1;i<m;i++){ pre = cur; cur = cur.next; } // m到n之间反转 for(int i=m;i<n;i++){ ListNode temp = cur.next;//记录当前节点的下一个节点 cur.next = temp.next;//将cur的next指针指向temp的下一个节点,断开前向后的 temp.next = pre.next;//temp的下一个节点指向pre.next即cur pre.next = temp;// 完成当前节点的反转 } return res.next; } }
假设节点为1 2 3 4 ,pre指向1,cur指向2 ,在断开2到3的链接之前必须要先记录3,否则一旦断开就找不到了,因此引入temp指向cur.next,记录这个顺序,也就是3,把2.next指向3.next(即4)实现断开,此时,3.next指向1.next,也就是2,反转一次,1.next指向3实现最终反转