题解 | 链表中的节点每k个一组翻转
链表中的节点每k个一组翻转
https://www.nowcoder.com/practice/b49c3dc907814e9bbfa8437c251b028e
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
#include <memory>
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @param k int整型
* @return ListNode类
*/
ListNode* reverseKGroup(ListNode* head, int k) {
// write code here
//采用分组递归的方法
ListNode* tail = head;
for(int i=0;i<k;i++)//通过循环找到该组的尾节点
{
if(tail == NULL)
{
return head;
}
tail = tail->next;
}
//进行普通的链表反转
ListNode* pre = NULL;
ListNode* cur = head;
while(cur != tail)
{
ListNode* temp = cur->next;
cur->next = pre;
pre = cur;
cur =temp;
}
//将反转前的头节点(也就是反转后的尾节点)跟下一组反转的链表连接
head->next = reverseKGroup(tail,k);
return pre;
}
};
查看21道真题和解析