思路:反转链表
首先记录需要进行几次翻转操作
写翻转函数,输入head tail 返回新的head
连接翻转后的子链表(循环)
/**
* 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:
ListNode* reverseKGroup(ListNode* head, int k) {
//首先记录需要进行几次翻转操作
//写翻转函数,输入head tail 返回新的head
//连接翻转后的子链表(循环)
int len = 0;
ListNode* p = head;
while(p!=NULL){
p = p->next;
len++;
}
int time = len/k;
ListNode* dummy = new ListNode(-1);
dummy->next = head;
auto pre = dummy;
while(time--){
auto cur = pre->next;
auto tail =pre;
for(int i=0;i<k;i++){
tail = tail->next;
}
reverse(cur,tail);
pre->next = tail;
pre = cur;
}
ListNode* res = dummy->next;
delete(dummy);
return res;
}
void reverse(ListNode*cur,ListNode*tail){
while(cur!=tail){
ListNode* nextcur = cur->next;
cur->next = tail->next ;
tail->next =cur;
cur = nextcur;
}
}
};