和PTA差不多
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2){
if(l1==NULL) return l2;
if(l2==NULL) return l1;
struct ListNode *l3;
l3 = (struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode *p;
p=l3;
struct ListNode *p1=l1;
struct ListNode *p2=l2;
while(p1&&p2){
if(p1->val<p2->val){
p->next=p1;
p1=p1->next;
}
else{
p->next=p2;
p2=p2->next;
}
p=p->next;
}
if(p1)
p->next=p1;
if(p2)
p->next=p2;
return l3->next;
}
不过看了官方的,可以不开辟空间,但是不会,以后再改进。
c好像只能
l3 = (struct ListNode*)malloc(sizeof(struct ListNode));
和new。new我还不会
参考官方改了下
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2){
struct ListNode *l3;
l3 = (struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode* prev = l3;
while (l1 != NULL && l2 != NULL) {
if (l1->val < l2->val) {
prev->next = l1;
l1 = l1->next;
} else {
prev->next = l2;
l2 = l2->next;
}
prev = prev->next;
}
prev->next = l1 == NULL ? l2 : l1;
return l3->next;
}