思路:模拟
遍历链表并计数,每遍历 k 个元素就进行一次翻转,并接回结果链表,代码如下:
class Solution { public: // 翻转一个长度为k的链表,返回新的头、尾指针 pair<ListNode*, ListNode*> revK(ListNode* head, ListNode* tail) { ListNode* prev = tail->next; ListNode* p = head; while (prev != tail) { ListNode* nex = p->next; p->next = prev; prev = p; p = nex; } return {tail, head}; } ListNode* reverseKGroup(ListNode* head, int k) { ListNode* dummyHead = new ListNode(0); // 定义哑结点 dummyHead->next = head; ListNode* pre = dummyHead; while (head) { ListNode* tail = pre; // 查看剩余部分长度是否大于等于 k for (int i = 0; i < k; ++i) { tail = tail->next; if (!tail) { return dummyHead->next; // 已经遍历到结尾,不足k个,直接返回 } } ListNode* ne = tail->next; tie(head, tail) = revK(head, tail); // 把子链表重新接回原链表 pre->next = head; tail->next = ne; pre = tail; head = tail->next; } return dummyHead->next; } };
全部评论
(0) 回帖