K 个一组翻转链表
给你一个链表,每k个节点一组进行翻转,请你返回翻转后的链表。
k是一个正整数,它的值小于或等于链表的长度。
如果节点总数不是k的整数倍,那么请将最后剩余的节点保持原有顺序。
进阶:
- 你可以设计一个只使用常数额外空间的算法来解决此问题吗?
- 你不能只是单纯的改变节点内部的值,而是需要实际进行节点交换。
示例 1:
输入:head = [1,2,3,4,5], k = 2
输出:[2,1,4,3,5]
示例 2:
输入:head = [1,2,3,4,5], k = 3
输出:[3,2,1,4,5]
示例 3:
输入:head = [1,2,3,4,5], k = 1
输出:[1,2,3,4,5]
示例 4:
输入:head = [1], k = 1
输出:[1]
提示:
- 列表中节点的数量在范围 sz 内
- 1 <= sz <= 5000
- 0 <= Node.val <= 1000
- 1 <= k <= sz
Solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
| #include <iostream> #include <vector> using namespace std;
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 (!head || k < 1 || !head->next) { return head; } ListNode *first = new ListNode(0); first->next = head; head = first; ListNode *last = first; int len = k; while (last != nullptr) { if (len != 0) { last = last->next; len--; continue; } len = k; ListNode *d1 = first->next; ListNode *d2 = d1->next; while (--len) { d1->next = d2->next; d2->next = first->next; first->next = d2; if (d2 == last) { last = d1; } d2 = d1->next; } first = last; len = k; } head = head->next; return head; } };
ListNode *createList(vector<int> &data) { ListNode *list = new ListNode(0); ListNode *temp = list; for (int i = 0; i < data.size(); ++i) { temp->next = new ListNode(data.at(i)); temp = temp->next; } return list->next; }
void printList(ListNode *head) { ListNode *dummy = head; while (dummy) { std::cout << dummy->val << " "; dummy = dummy->next; } std::cout << std::endl; }
int main() { vector<int> data = {1, 2, 3, 4, 5}; ListNode *input = createList(data); ListNode *result; result = Solution().reverseKGroup(input, 3); printList(result);
input = createList(data); result = Solution().reverseKGroup(input, 2); printList(result);
input = createList(data); result = Solution().reverseKGroup(input, 1); printList(result);
data = {1, 2, 3, 4, 5, 6}; input = createList(data); result = Solution().reverseKGroup(input, 2); printList(result);
input = createList(data); result = Solution().reverseKGroup(input, 3); printList(result); }
|