题解 | #合并k个已排序的链表#

合并k个已排序的链表

https://www.nowcoder.com/practice/65cfde9e5b9b4cf2b6bafa5f3ef33fa6

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 * };
 */
/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param lists ListNode类一维数组 
 * @param listsLen int lists数组长度
 * @return ListNode类
 */

 

struct ListNode* Merge(struct ListNode* pHead1, struct ListNode* pHead2 ) {
    // write code here
    struct ListNode* temp1 = (struct ListNode*)malloc(sizeof(struct ListNode));
    struct ListNode* temp2 = (struct ListNode*)malloc(sizeof(struct ListNode));
    struct ListNode* result = (struct ListNode*)malloc(sizeof(struct ListNode) * 5001);

    temp1 = pHead1;
    temp2 = pHead2;

    struct ListNode* cur ;
    cur = result;
    while((temp1 != NULL) || (temp2 != NULL))
    {

        if((temp1 != NULL) && (temp2 != NULL))
        {

            if(temp1->val <= temp2->val)
            {
                printf("111  p1 %d  p2 %d  cur %d\n",temp1->val, temp2->val, cur->val);
                cur->next = temp1;
                cur = temp1;
                temp1 = temp1->next;
            } else {
                printf("222  p1 %d  p2 %d cur %d\n",temp1->val, temp2->val, cur->val);
                cur->next = temp2;
                cur = temp2;
                temp2 = temp2->next;
            }
        } else if((temp1 == NULL)) {
            cur->next = temp2;
            cur = temp2;
            temp2 = NULL;
        } else if((temp2 == NULL)) {
            cur->next = temp1;
            cur = temp1;
            temp1 = NULL;
        }
    }
    printf("=== %d\n", result->val );

    return result->next;
}


struct ListNode* mergeKLists(struct ListNode** lists, int listsLen ) {
    // write code here
    struct ListNode* result = (struct ListNode*)malloc(sizeof(struct ListNode) * 5001);
    result = NULL;
    int count = listsLen;
    while(count)
    {
    printf("=== count %d\n", count );

        result = Merge(result, lists[(listsLen-count)]);
        count--;
    }
    return result;
}


全部评论

相关推荐

07-01 19:00
门头沟学院 Java
点赞 评论 收藏
分享
06-20 19:40
中原工学院 Java
网络存储:十几天不会让你拉人办卡就结束了吧?
点赞 评论 收藏
分享
半解316:内容充实,细节需要修改一下。 1,整体压缩为一页。所有内容顶格。 2,项目描述删除,直接写个人工作量 修改完之后还需要建议,可以私聊
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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