https://leetcode.cn/problems/reverse-nodes-in-k-group/description/
https://www.nowcoder.com/feed/main/detail/37b33edb0a554c2eb932904c2fe19189?sourceSSR=users
https://www.nowcoder.com/discuss/629693483137163264?sourceSSR=search
https://www.nowcoder.com/feed/main/detail/e858f4b584af492c9f13474f490af198
https://www.nowcoder.com/discuss/658671032420560896
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
// 判断边界条件
if (head == null || head.next == null) return head;
int count = 0;
ListNode cur = head;
// 如果 cur 不为空且 count 不等与 k继续循环
while (cur != null && count != k) {
cur = cur.next;
count++;
}
if (count == k) {
// 递归
cur = reverseKGroup(cur, k);
while (count-- > 0) {
ListNode temp = head.next; // 存储下一个节点
head.next = cur; // 将当前节点的next域指向前一个节点
cur = head; // prev 指针向后移动
head = temp; // curr 指针向后移动
}
head = cur;
}
// 5 -> null
return head;
}
}
https://www.nowcoder.com/feed/main/detail/7fae92ade928425a9ea7439c4777b8dc
https://www.nowcoder.com/discuss/629693483137163264?sourceSSR=search