首页 > 代码库 > LeetCode Reverse Nodes in k-Group
LeetCode Reverse Nodes in k-Group
class Solution {public: ListNode *reverseKGroup(ListNode *head, int k) { if (k < 1) return head; ListNode* last = NULL; ListNode* newhead = NULL; ListNode* cur = head; bool fullcut = false; while (cur != NULL) { ListNode* remain_head = cut(cur, k, fullcut); ListNode* rtail = cur; ListNode* rhead = fullcut ? reverse(cur) : cur; cur = remain_head; if (newhead == NULL) { newhead = rhead; } else { last->next = rhead; } last = rtail; } return newhead; } ListNode* cut(ListNode* head, int k, bool &full) { ListNode* cur = head; ListNode* pre = NULL; while (k > 0 && cur != NULL) { k--; pre = cur; cur = cur->next; } if (pre != NULL) pre->next = NULL; full = k == 0; return cur; } ListNode* reverse(ListNode* head) { ListNode* cur = head; ListNode* pre = NULL; while (cur != NULL) { ListNode* t = cur->next; cur->next = pre; pre = cur; cur = t; } return pre; }};
对于是否完全是k个元素的处理有点脏(几个变量的含义与刚好是k个元素时不一致,不过因为不是k个的情况只会发生一次且是最后一次迭代,因而这些变量变脏了也无妨),不过时间有点长130ms+不知是否可以继续改进
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。