Merge two sorted linked lists and return it as a new list. e new list should be made by splicing
together the nodes of the first two lists.
//
// start: merge two sorted lists
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) // 注意其中一个链表先结束
{
ListNode head(-1); // 为避免第一个指针为空,则新建立一个初始节点,后面略过它
for(ListNode *p = &head; l1 || l2)
{
int val1 = l1 == NULL ? INT_MAX : l1->val; // 每次取较小的那个,所以可以将空指针对应的值设为max,这样后面就不用判断具体哪个指针为空而重复代码
int val2 = l2 == NULL ? INT_MAX : l2->val;
if(val1 <= val2)
{
p->next = l1; // 不开新空间
l1 = l1->next;
}
else
{
p->next = l2;
l2 = l2->next;
}
}
return head.next;
}
// end
//