题解 | #合并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;
}
};
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;
}
};