题目描述
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
分析
简单题,考察链表的操作。不过链表的操作需要注意判断链表是否为空,这个几乎是每道链表题都需要注意的地方。另外,将头结点进行单独处理可以简化后续操作。这道题还有一个地方可以进行优化,如果一条链表已经为空,那么就可以直接将后续节点直接连接到结果链表上。
AC代码如下:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode* result = NULL;//结果
//判断输入是否为空
if(l1 == NULL)
{
return l2;
}
if(l2 == NULL)
{
return l1;
}
//头结点单独处理
if(l1->val < l2->val)
{
result = new ListNode(l1->val);
l1 = l1->next;
}
else
{
result = new ListNode(l2->val);
l2 = l2->next;
}
ListNode* temp = result;
while(l1 != NULL || l2 != NULL)//主循环
{
if(l1 == NULL)//判断是否有一条链表已经为空
{
temp->next = l2;
break;
}
if(l2 == NULL)
{
temp->next = l1;
break;
}
if(l1->val < l2->val)
{
temp->next = new ListNode(l1->val);
l1 = l1->next;
}
else
{
temp->next = new ListNode(l2->val);
l2 = l2->next;
}
temp = temp->next;
}
return result;
}
};