题解 | #牛群的重新分组#

牛群的重新分组

https://www.nowcoder.com/practice/267c0deb9a6a41e4bdeb1b2addc64c93

将链表中的数据提取到带有序号的映射中,然后将节点交换,最后按交换后的顺序放入向量中组合成符合题目要求的链表。

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 *	ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
class Solution {
private:
    map<int, ListNode*> map;
    vector<ListNode*> list;
    int group = 0;
    int length = 0;
    int count = 0;
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param head ListNode类 
     * @param k int整型 
     * @return ListNode类
     */
    ListNode* reverseKGroup(ListNode* head, int k) {
        // write code here
        calLength(head);
        group = length / k;
        collect(head);
        count = 0;
        reverse(k);
        head = list.at(0);
        count = 1;
        creat(head);
        return head;
    }

    void calLength(ListNode* head) {
        length++;
        if(head->next == nullptr) {
            return;
        }
        calLength(head->next);
    }

    void collect(ListNode* head) {
        map.insert({count, head});
        count++;
        if(head->next == nullptr) {
            return;
        }
        collect(head->next);
    }

    void reverse(int k) {
        for(int i = 0; i < group; i++) {
            for(int j = (i + 1) * k - 1; j >= (i + 1) * k - k; j--) {
                list.push_back(map.at(j));
                count++;
            }
        }
        //if(count < length - 1) {
            for(int i = count; i < length; i++) {
                list.push_back(map.at(i));
            }
        //}
    }

    void creat(ListNode* head) {
        head->next = list.at(count);
        if(count == list.size() - 1) {
            head->next->next = nullptr;
        }
        count++;
        if(count < list.size()) {
            creat(head->next);
        }
    }
};

中等(算法题解) 文章被收录于专栏

中等难度题目

全部评论

相关推荐

03-31 18:02
门头沟学院 Java
白日梦想家_等打包版:不要的哦佛给我
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务