题解 | #链表内指定区间反转# 一次遍历,简单明了
链表内指定区间反转
https://www.nowcoder.com/practice/b58434e200a648c589ca2063f1faf58c
遍历一遍链表,记录下index为m-1和m的节点node1和node2,当m<index<=n时,当前节点指向前一个节点进行反转,最后index等于n时再利用记录下来的node1和node2完善结果。
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 int index = 1; ListNode dummy = new ListNode(0); dummy.next = head; ListNode prev = dummy; ListNode node1 = dummy; ListNode node2 = dummy; while (head != null) { ListNode next = head.next; if (index == m - 1) { node1 = head; } if (index == m) { node2 = head; } if (m < index && index <= n) { head.next = prev; } if (index == n) { node1.next = head; node2.next = next; } prev = head; head = next; index++; } return dummy.next; } }