题解 | #牛群的重新排列#
牛群的重新排列
https://www.nowcoder.com/practice/5183605e4ef147a5a1639ceedd447838
题目考察的知识点
考察链表的相关操作
题目解答方法的文字分析
对于本题,仍然构建头结点进行辅助。找到left的前一个节点保存下来,将left~right之间的元素进行逆序,随后再将之前保存的前一个节点和right节点连接。left和right后面节点连接即可。
本题解析所用的编程语言
使用Java解决
完整且正确的编程代码
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
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode pre = dummy;
for (int i = 1; i < left; i++) {
pre = pre.next;
}
ListNode cur = pre.next;
for (int i = left; i < right; i++) {
ListNode tmp = cur.next;
cur.next = tmp.next;
tmp.next = pre.next;
pre.next = tmp;
}
return dummy.next;
}
}

