将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2){
struct ListNode *result = (struct ListNode*) malloc(sizeof(struct ListNode));
result->next = NULL;
struct ListNode *p = l1, *q = l2, *r, *temp = result;
while(p&&q){
if(p->val > q->val){
temp->next = q;
temp = q;
q=q->next;
}
else{
temp->next = p;
temp = p;
p=p->next;
}
}
while(p){
temp->next = p;
temp = p;
p = p->next;
}
while(q){
temp->next = q;
temp = q;
q = q->next;
}
p = result;
printf("%d %d", result, result->next);
if(!result->next)
return NULL;
result = result->next;
free(p);
return result;
}