Reverse Nodes in k-Group

描述

Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.

If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.

You may not alter the values in the nodes, only nodes itself may be changed.

Only constant memory is allowed.

For example,Given this linked list: 1->2->3->4->5

For k = 2, you should return: 2->1->4->3->5

For k = 3, you should return: 3->2->1->4->5

分析

递归版

  1. // Reverse Nodes in k-Group
  2. // 递归版,时间复杂度O(n),空间复杂度O(1)
  3. class Solution {
  4. public:
  5. ListNode *reverseKGroup(ListNode *head, int k) {
  6. if (head == nullptr || head->next == nullptr || k < 2)
  7. return head;
  8. ListNode *next_group = head;
  9. for (int i = 0; i < k; ++i) {
  10. if (next_group)
  11. next_group = next_group->next;
  12. else
  13. return head;
  14. }
  15. // next_group is the head of next group
  16. // new_next_group is the new head of next group after reversion
  17. ListNode *new_next_group = reverseKGroup(next_group, k);
  18. ListNode *prev = NULL, *cur = head;
  19. while (cur != next_group) {
  20. ListNode *next = cur->next;
  21. cur->next = prev ? prev : new_next_group;
  22. prev = cur;
  23. cur = next;
  24. }
  25. return prev; // prev will be the new head of this group
  26. }
  27. };

迭代版

  1. // Reverse Nodes in k-Group
  2. // 迭代版,时间复杂度O(n),空间复杂度O(1)
  3. class Solution {
  4. public:
  5. ListNode *reverseKGroup(ListNode *head, int k) {
  6. if (head == nullptr || head->next == nullptr || k < 2) return head;
  7. ListNode dummy(-1);
  8. dummy.next = head;
  9. for(ListNode *prev = &dummy, *end = head; end; end = prev->next) {
  10. for (int i = 1; i < k && end; i++)
  11. end = end->next;
  12. if (end == nullptr) break; // 不足 k 个
  13. prev = reverse(prev, prev->next, end);
  14. }
  15. return dummy.next;
  16. }
  17. // prev 是 first 前一个元素, [begin, end] 闭区间,保证三者都不为 null
  18. // 返回反转后的倒数第1个元素
  19. ListNode* reverse(ListNode *prev, ListNode *begin, ListNode *end) {
  20. ListNode *end_next = end->next;
  21. for (ListNode *p = begin, *cur = p->next, *next = cur->next;
  22. cur != end_next;
  23. p = cur, cur = next, next = next ? next->next : nullptr) {
  24. cur->next = p;
  25. }
  26. begin->next = end_next;
  27. prev->next = end;
  28. return begin;
  29. }
  30. };

相关题目

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/cpp/linear-list/linked-list/reverse-nodes-in-k-group.html