题解 | #牛群的重新分组#
牛群的重新分组
https://www.nowcoder.com/practice/267c0deb9a6a41e4bdeb1b2addc64c93
题目考察的知识点是:
本题主要考察链表的反转操作。
题目解答方法的文字分析:
这道题需要改变头结点,所以新建一个头结点,然后需要翻转单链表,翻转单链表可以用链表头插, 将需要翻转的结点一个一个头插到某个结点的后面,总之,这道题用头插不是很容易。
本题解析所用的编程语言:
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 k int整型 * @return ListNode类 */ public ListNode reverseKGroup (ListNode head, int k) { // write code here if (head == null) { return null; } int n = 0; ListNode cur = head; while (cur != null) { n += 1; cur = cur.next; } if (n < k) { return head; } ListNode pre = head; cur = head.next; int index = 1; while (index < k) { ListNode next = cur.next; cur.next = pre; pre = cur; cur = next; index += 1; } head.next = reverseKGroup(cur, k); return pre; } }#题解#