给你一个链表,每 k 个节点一组进行翻转,请你返回翻转后的链表。
k 是一个正整数,它的值小于或等于链表的长度。
如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。
示例:
给你这个链表:1->2->3->4->5
当 k = 2 时,应当返回: 2->1->4->3->5
当 k = 3 时,应当返回: 3->2->1->4->5
/**
* 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* ans = NULL;
ListNode* reverse(ListNode* root, int k) {
if(k == 1 || root == NULL) return root;
ListNode* tem = reverse(root -> next, k - 1);
if(tem != NULL) tem -> next = root, root -> next = NULL;
return root;
}
ListNode* reverseKGroup(ListNode* head, int k) {
ListNode* tem = head, *ans = NULL, *pre = NULL, *end = head;
int f = 0;
while(tem != NULL) {
ListNode* cur = NULL;
int i;
for(i = 1; i < k && end -> next != NULL; i ++)
end = end -> next;
cur = end -> next;
if(ans == NULL) ans = end;
if(f)
pre -> next = end;
if(i != k) {
pre -> next = tem;
break;
}
pre = reverse(tem, k);
tem = cur, end = cur;
f++;
}
return ans;
}
};