题解 | #链表中的节点每k个一组翻转#
链表中的节点每k个一组翻转
https://www.nowcoder.com/practice/b49c3dc907814e9bbfa8437c251b028e
//第一步:先看链表长度小于3的,分k=1,k=2直接返回
//第二步:链表长度大于3,做部分反转,每次翻转之后看剩余节点数是否大于等于k,大于等于k继续反转,否则退出循环,结束反转
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
#include <cstddef>
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @param k int整型
* @return ListNode类
*/
ListNode* reverseKGroup(ListNode* head, int k) {
// write code here
if (head == nullptr || head->next == nullptr) {
return head;
}
if (head->next->next == nullptr) {
if (k == 2) {
auto* dummy = new ListNode(0);
dummy->next = head;
ListNode* pre = head;
ListNode* cur = pre->next;
pre->next = cur->next;
cur->next = dummy->next;
dummy->next = cur;
return dummy->next;
} else {
return head;
}
}
auto* dummy = new ListNode(0);
dummy->next = head;
ListNode* pre = head;
ListNode* cur = pre->next;
ListNode* L = dummy;
int flag=0;
while (cur) {
for (int i = 0; i < k - 1; i++) {
pre->next = cur->next;
cur->next = L->next;
L->next = cur;
cur = pre->next;
}
for(int i=0;i<k-1;i++)
{
if(cur==nullptr)
{
flag=1;
break;
}
cur=cur->next;
}
if(flag==1)
break;
L = pre;
pre = L->next;
cur = pre->next;
}
return dummy->next;
}
};
查看15道真题和解析