题目描述:将已排好序的两个链表连接到一起,返回连接的链表。
以下是C++实现,如有需要,请访问我的Github获取包含测试程序的完整源码。
20180731更新:给出递归和非递归两种解法
//递归解法,执行效率较高
/**
* 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)
{
if(l1 == NULL)
{
return l2;
}
if(l2 == NULL)
{
return l1;
}
if(l1->val >= l2->val)
{
ListNode* temp = l2;
temp->next = mergeTwoLists(l1,l2->next);
return temp;
}
else
{
ListNode* temp = l1;
temp->next = mergeTwoLists(l1->next, l2);
return temp;
}
}
};
//非递归解法
/**
* 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) {
if(l1 == NULL && l2 == NULL)
return NULL;
//添加一个链表头
ListNode* new_node = new ListNode(0);
ListNode* pre = new_node;
while(l1 != NULL && l2 != NULL)
{
if(l1->val < l2->val)
{
pre->next = l1;
l1 = l1->next;
}
else
{
pre->next = l2;
l2 = l2->next;
}
pre = pre->next;
}
if(l1)
pre->next = l1;
else
pre->next = l2;
return new_node->next;
}
};