输入两个递增排序的链表,合并这两个链表并使新链表中的节点仍然是递增排序的。
示例1:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
限制:
0 <= 链表长度 <= 1000
解:
原地修改:双指针各指一个原链表,比较大小,添加较小节点至合并链表,双指针交替前进。
时间复杂度O(m+n),空间复杂度O(1)。
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
//原地修改
ListNode* head = new ListNode; //伪头结点,首次建立l3时没有头节点,引入该节点,将各节点加入该节点后
ListNode* l3 = head;
while(l1 != NULL && l2 != NULL)
{
if(l1->val < l2->val)
{
l3->next = l1;
l1 = l1->next;
}
else
{
l3->next = l2;
l2 = l2->next;
}
l3 = l3->next;
}
l3->next = l1 ? l1:l2;
return head->next; //真头结点
//递归
//函数功能:返回两参数中节点值较小的节点,并将其链至当前节点尾部
if(l1 == NULL) return l2;
if(l2 == NULL) return l1;
if(l1->val < l2->val)
{
l1->next = mergeTwoLists(l1->next,l2);
return l1;
}
l2->next = mergeTwoLists(l1,l2->next);
return l2;
//新建链表
/*ListNode* head = NULL;
ListNode* cur1 = l1;
ListNode* cur2 = l2;
ListNode* cur3 = new ListNode;
while(cur1 && cur2)
{
ListNode* node = new ListNode;
if(cur1->val <= cur2->val)
{
node->val = cur1->val;
cur1 = cur1->next;
}
else
{
node->val = cur2->val;
cur2 = cur2->next;
}
cur3->next = node;
cur3 = cur3->next;
if(!head) head = cur3;
}
ListNode* cur = cur1 ? cur1:cur2;
for(cur;cur;cur = cur->next)
{
ListNode*node = new ListNode;
node->val = cur->val;
cur3->next = node;
cur3 = cur3->next;
if(!head) head = cur3;
}
return head;*/
}
};