题目描述
给你一个链表,每 k 个节点一组进行翻转,请你返回翻转后的链表。k 是一个正整数,它的值小于或等于链表的长度。如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。
链接:https://leetcode-cn.com/problems/reverse-nodes-in-k-group
示例
输入:head = [1,2,3,4,5], k = 2输出:[2,1,4,3,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* reverseKGroup(ListNode* head, int k) {ListNode *slow, *fast, *last_k_pre=new ListNode();ListNode *ahead;slow = head;fast = head;int cnt, global_seg_cnt=0;while (fast != NULL) {cnt = 1;//切分段while (cnt < k) {fast = fast->next;if (fast == NULL)break;cnt++;}// 当前段的长度小于Kif (cnt < k) {last_k_pre->next = slow;if (global_seg_cnt == 0)ahead = last_k_pre;break;}ListNode* next_head = fast->next;// 翻转当前段ListNode *pre = NULL, *curr_tail = slow;while (slow != next_head) {ListNode* temp = slow->next;slow->next = pre;pre = slow;slow = temp;}last_k_pre->next = fast;if (global_seg_cnt == 0)ahead = last_k_pre;last_k_pre = curr_tail;fast = next_head;slow = next_head;global_seg_cnt++;}return ahead->next;}};
