题解 | #链表内指定区间反转#
链表内指定区间反转
https://www.nowcoder.com/practice/b58434e200a648c589ca2063f1faf58c
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) { // write code here ListNode dummy = new ListNode(-1); dummy.next = head; ListNode cur = null; ListNode tmp = null; ListNode pre = dummy; //pre 指代虚拟节点往后走 for(int i = 1;i<m ;i++){ pre = pre.next; //找到要反转区间的前一个节点 } cur = pre.next; //类似于递归 for(int i = 0;i < n-m ;i++){ //类似于抽屉抽出法,一次抽出一个,抽n-m次 tmp = cur.next; cur.next = tmp.next; tmp.next = pre.next; pre.next = tmp; } return dummy.next; //返回虚拟节点的后一个节点 } }