首页 > 其他 > 详细

LeetCode Reverse Nodes in k-Group

时间:2014-07-28 11:22:20      阅读:301      评论:0      收藏:0      [点我收藏+]
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+不知是否可以继续改进

LeetCode Reverse Nodes in k-Group,布布扣,bubuko.com

LeetCode Reverse Nodes in k-Group

原文:http://www.cnblogs.com/lailailai/p/3872161.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!