题解 | #牛群的重新排列#
牛群的重新排列
https://www.nowcoder.com/practice/5183605e4ef147a5a1639ceedd447838
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 left int整型
* @param right int整型
* @return ListNode类
*/
public ListNode reverseBetween (ListNode head, int left, int right) {
// write code here
if (head == null || left == right) {
return head;
}
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode prev = dummy;
// 移动prev到left的前一个节点
for (int i = 1; i < left; i++) {
prev = prev.next;
}
// 初始化指针,用于反转链表
ListNode current = prev.next;
ListNode next = null;
// 开始反转
for (int i = left; i < right; i++) {
next = current.next;
current.next = next.next;
next.next = prev.next;
prev.next = next;
}
return dummy.next;
}
}
- 创建一个虚拟头节点(dummy),并将其连接到原始链表的头部,以便简化反转操作。
- 通过移动prev指针到left前一个节点,为反转操作做准备。
- 使用两个指针current和next,其中current用于迭代遍历待反转的节点,next用于保存current的下一个节点。
- 在从left到right的范围内,通过修改节点的next引用来实现节点的反转。
- 在每次迭代中,将current节点移出原链表,将其插入到prev节点之后,同时更新prev指针。
- 完成循环后,返回虚拟头节点的next,即反转后的链表头。
