1、遍历链表得到链表的长度length;
2、得到链表的长度是为了获取链表翻转的次数(length / k),循环翻转链表即可。
时间复杂度:o(n)
空间复杂度:o(1)
class Solution { public: ListNode* reverseKGroup(ListNode* head, int k) { //特殊情况处理 if (k == 1 || head == nullptr || head->next == nullptr) return head; //设置表头 ListNode* res = new ListNode(0); res->next = head; ListNode* pre = res; ListNode* cur = head; //获取链表长度 int length = 0; ListNode* phead = head; while(phead != nullptr) { length++; phead = phead->next; } if(k > length) return head; else { //翻转链表 for(int i = 0; i < length / k; i++) { for(int i = 1; i < k; i++) { ListNode* ptemp = cur->next; cur->next = ptemp->next; ptemp->next = pre->next; pre->next = ptemp; } pre = cur; cur = cur->next; } } return res->next; } };