Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
Example:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2)
{
if(NULL == l1 && NULL != l2)
return l2;
else if(NULL == l2 && NULL != l1)
return l1;
else if (NULL == l1 && NULL == l2)
return NULL;
struct ListNode *head = NULL;
/*返回新链表的头结点*/
struct ListNode *ret = NULL;
/*确定链表头*/
if(l1->val < l2->val)
{
head = l1;
l1 = l1->next;
}
else
{
head = l2;
l2 = l2->next;
}
/*保存链表头*/
ret = head;
while(l1 &&l2)
{
if(l1->val >l2->val)
{
head->next = l2;
l2 = l2->next;
}
else
{
head->next = l1;
l1 = l1->next;
}
/*新插入的结点next置NULL*/
head->next->next = NULL;
head = head->next;
}
if(l1)
head->next = l1;
else if (l2)
head->next = l2;
return ret;
}