题解 | #链表内指定区间反转#
链表内指定区间反转
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 /*if (head == null || head.next == null){ return head; } // 左指针 ListNode p = head; ListNode left = null; ListNode mNode = null; // 末尾 ListNode nNode = null; // 右指针 ListNode right = null; // 记录需要反转的链表前一位 ListNode prev = null; for (int i = 1; i <= m-1; i++) { prev = p; p = p.next; } for (int i = 1; i <= m; i++) { mNode = p; p = p.next; } p = head; for (int i = 1; i <= n; i++) { nNode = p; p = p.next; } prev = nNode.next;*/ ListNode res = new ListNode(-1); res.next = head; ListNode pre = res; ListNode cur = head; for (int i = 1; i < m; i++) { pre = cur; cur = cur.next; } // 反转链表 for (int i = m; i < n; i++) { ListNode temp = cur.next; cur.next = temp.next; temp.next = pre.next; pre.next = temp; } return res.next; } }