首页 > 代码库 > Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. k is a positive integer and is less than or equal to the length of the linked list. If the number of
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. k is a positive integer and is less than or equal to the length of the linked list. If the number of
class Solution { public: ListNode *reverseKGroup(ListNode *head, int k) { if (!head || !(head->next) || k < 2) return head; // count k nodes ListNode *nextgp = head; for (int i = 0; i < k; i++) if (nextgp) nextgp = nextgp->next; else return head; // reverse ListNode *prev = NULL, *cur = head, *next = NULL; while (cur != nextgp) { next = cur->next; if (prev) cur->next = prev; else cur->next = reverseKGroup(nextgp, k); prev = cur; cur = next; } return prev; } };
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. k is a positive integer and is less than or equal to the length of the linked list. If the number of
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。