题解 | #牛群的重新分组#
牛群的重新分组
https://www.nowcoder.com/practice/267c0deb9a6a41e4bdeb1b2addc64c93
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @param k int整型
* @return ListNode类
*/
ListNode* reverseKGroup(ListNode* head, int k) {
auto dummy = new ListNode(-1);//创建临时头结点
dummy->next = head;
ListNode* pre = dummy;
ListNode* cur = head;
while (cur != nullptr) {
//保存每一组的链表头部,类似带头结点的局部链表
ListNode* ehead = pre;
//组内成员不足k个的处理
ListNode* flag = cur;
for (int i = 1; i < k; i++) {
flag = flag->next;
if (flag == nullptr) {
break;
}
}
//组内有k个元素时才反转
if (flag) {
//每k个一组链表反转
for (int i = 1; i <= k; i++) {
ListNode* temp = cur->next;
cur->next = pre;
pre = cur;
cur = temp;
}
ehead->next->next = cur;
ehead->next = pre;
for (int i = 1; i < k; i++) {
pre = pre->next;//更新pre为新的前驱
}
} else {
break;
}
}
return dummy->next;
}
};
查看23道真题和解析
