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

合并k个已排序的链表

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

/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
            val(x), next(NULL) {
    }
};*/
class Solution {
public:
    ListNode* Merge(ListNode* pHead1, ListNode* pHead2) {
        ListNode* r = (ListNode*)malloc(sizeof(ListNode));
        r->next = NULL;
        ListNode* newList = (ListNode*)malloc(sizeof(ListNode));
        newList = r;
        while(pHead1 != NULL && pHead2 != NULL){
            if(pHead1->val > pHead2->val){
                r->next = pHead2;
                pHead2 = pHead2->next;
            }else{
                 r->next = pHead1;
                pHead1 = pHead1->next;
            }
            r = r->next;
        }
        if(pHead1 != NULL) r->next = pHead1;
        if(pHead2 != NULL) r->next = pHead2;
        return newList->next; 
    }
};
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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