题目描述
给你一个链表,每 k 个节点一组进行翻转,请你返回翻转后的链表。
k 是一个正整数,它的值小于或等于链表的长度。
如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。
算法
细节1、该题使用辅助函数reverse对区间[a, b)之间的结点进行反转
cur == b的时候退出,注意该函数返回pre,所以反转的区间是左开右闭
细节2、在函数reverseKGroup内,ref指向[a, b)反转后的结点,所以指向的b前一个结点,再让a的next指向reverseKGroup(b, k)的返回结果
细节3、最后返回ref
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
//先实现一个反转链表,反转[a, b)之间的结点
ListNode* reverse(ListNode* a, ListNode* b)
{
ListNode* pre, *cur, *nxt;
pre = nullptr;
cur = a;
nxt = a;
while(cur != b)
{
nxt = cur->next;
cur->next = pre;
//改变指针指向
pre = cur;
cur = nxt;
}
a->next = cur;
return pre;
}
ListNode* reverseKGroup(ListNode* head, int k) {
ListNode* a, *b;
a = b = head;
for(int i = 0; i < k; i++)
{
if(b == nullptr)
{
return head;
}
b = b->next;
}
ListNode* ref = reverse(a, b);
a->next = reverseKGroup(b, k);
return ref;
}
};
迭代与递归模板比较
迭代与递归方法对比
https://blog.csdn.net/weixin_45066412/article/details/115471285