题解 | #牛的品种排序IV#

牛的品种排序IV

https://www.nowcoder.com/practice/bd828af269cd493c86cc915389b02b9f

这题的解法与NB12 牛群的身高排序一致,更详细的见上一题

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 *	ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param head ListNode类 
     * @return ListNode类
     */
    
    ListNode* MyMerge(ListNode* h1, ListNode* h2){
        if(h1 == nullptr){
            return h2;
        }
        else if(h2 == nullptr){
            return h1;
        }
        else{
            ListNode* sentry = new ListNode(-1);
            ListNode* excute = sentry;
            while(h1 != nullptr && h2 != nullptr){
                if(h1->val > h2->val){ // 因为升序,所以要小的
                    excute->next = h2;
                    h2 = h2->next;
                }else {
                    excute->next = h1;
                    h1 = h1->next;
                }
                excute = excute->next;
            }
            if(h1 != nullptr){
                excute->next = h1;
            }else {
                excute->next = h2;
            }
            return sentry->next;
        }
    }

    ListNode* sortCowsIV(ListNode* head) {
        // write code here
        if(head == nullptr || head->next == nullptr){
            return head;
        }
        ListNode* left = head;
        ListNode* midle = head->next;
        ListNode* right = head->next->next;
        while(right != nullptr && right->next != nullptr){
            left = left->next;
            midle = midle->next;
            right = right->next->next;
        }
        left->next = nullptr;
        return MyMerge(sortCowsIV(head), sortCowsIV(midle));
    }
};

全部评论

相关推荐

程序员牛肉:主要是因为小厂的资金本来就很吃紧,所以更喜欢有实习经历的同学。来了就能上手。 而大厂因为钱多,实习生一天三四百的就不算事。所以愿意培养你,在面试的时候也就不在乎你有没有实习(除非是同级别大厂的实习。) 按照你的简历来看,同质化太严重了。项目也很烂大街。 要么换项目,要么考研。 你现在选择工作的话,前景不是很好了。
点赞 评论 收藏
分享
Ncsbbss:又想干活又想要工资,怎么什么好事都让你占了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务