合并两个有序链表的递归和非递归实现

递归实现

ListNode* mergeList(ListNode* head1, ListNode* head2)
{
	if(head1 == nullptr)
		return head2;
	else if(head2 == nullptr)
		return head1;
	
	ListNode* res = nullptr;
	if(head1 -> val < head2 -> val) {
		res = head1;
		res -> next = mergeList(head1 -> next, head2);
	} else {
		res = head2;
		res -> next = mergeList(head1, head2 -> next);
	}
	
	return res;
}

非递归实现

ListNode* mergeList(ListNode* head1, ListNode* head2)
{
	ListNode* dummy = new ListNode(-1);
	ListNode* last = dummy;
	while(head1 && head2) {
		if(head1 -> val < head2 -> val) {
			last -> next = head1;
			last = last -> next;
			head1 = head1 -> next;
		} else {
			last -> next= head2;
			last = last -> next;
			head2 = head2 -> next;
		}
	}
	if(head1)
		last -> next = head1;
	else if(head2)
		last -> next = head2;
	
	ListNode* res = dummy -> next;
	delete dummy;
	return res;
}

你可能感兴趣的:(数据结构与算法)