两个链表分别有序,合并为一个有序的链表
如输入1->2->3 2->4->5 输出1->2->2->3->4->5
方法一:
分别用两个指针指向当前正在处理的节点,较小者插入合并后链表的尾部,所以需要一个指针保存合并后链表的尾部
Node* merge_list(Node* head1, Node* head2)
{
Node* head = NULL;
Node* tail = NULL;
Node* tmp = NULL;
while (head1 && head2)
{
if (head1->data < head2->data)
{
tmp= head1;
head1 = head1->next;
}
else
{
tmp = head2;
head2 = head2->next;
}
if (head == NULL)
head = tmp;
else
tail->next = tmp;
tail = tmp;
}
if (head1 != NULL) tail->next = head1;
if (head2 != NULL) tail->next = head2;
return head;
}
方法二:递归
合并后的头节点为两链表头节点的较小者,然后递归得到合并后的头节点
Node* merge_list2(Node* head1, Node* head2)
{
if (head1 == NULL) return head2;
if (head2 == NULL) return head1;
if (head1->data < head2->data)
{
head1->next = merge_list2(head1->next, head2);
return head1;
}
else
{
head2->next = merge_list2(head1, head2->next);
return head2;
}
}