题目
Merge Two Sorted Lists
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.
标签
Linked List
难度
简单
分析
题目意思是合并两个排好序的链表,并返回新的链表。解题思路是先找到链表的头,如果L1的第一个元素比较小,新链表的头结点就指向L1,如果L2的第一个元素比较小,新链表的头结点就指向L2。剩下的就是逐个比较剩余L1和L2里的元素。需要注意的是,最后是否比较结束了。
C代码实现
struct ListNode *head;
struct ListNode *ret;
if(!l1 && l2)
return l2;
if(l1&&!l2)
return l1;
if(!l1 && !l2)
return 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 = l1;
l1 = l1->next;
}
else
{
head->next = l2;
l2 = l2->next;
}
head->next->next = NULL;
head = head->next;
}
if(l1)
head->next = l1;
else if(l2)
head->next = l2;
return ret;