题解 | #牛群的重新分组#
牛群的重新分组
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 { public ListNode reverseKGroup(ListNode head, int k) { ListNode dummy = new ListNode(0); dummy.next = head; ListNode prev = dummy; ListNode curr = head; int length = 0; while (head != null) { length++; head = head.next; } for (int i = 0; i < length / k; i++) { for (int j = 1; j < k; j++) { ListNode next = curr.next; curr.next = next.next; next.next = prev.next; prev.next = next; } prev = curr; curr = curr.next; } return dummy.next; } }