首页 > 代码库 > 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+不知是否可以继续改进