链表操作问题,熟悉操作后就好做了,
每次选取k个,进行翻转,记录头尾,和上一次的末尾节点,进行反转拼接即可。
在纸上画出来就清晰了
/**
* 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) {
if(k<=1)return head;
//new ListNode(0,head)
ListNode* ans = new ListNode(0);
ListNode* pre = head;
ListNode* lst_end = ans;
ListNode* tp = head;
int nm=k,fg=1;
while(tp){
auto to = tp->next;
nm--;
//进行交换
if(nm==0 && k > 1){
lst_end ->next = tp;
lst_end = pre;
auto lst = pre;
pre=pre->next;
lst->next = tp->next;
while(lst!=tp){
auto nxt = pre->next;
pre->next = lst;
lst = pre;
pre = nxt;
}
nm=k;
}
tp=to;
}
return ans->next;
}
};