leetcode-合并两个有序链表-13

合并两个有序链表

题目要求
  将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例1:
输入:l1 = [1,2,4], l2 = [1,3,4]
输出:[1,1,2,3,4,4]
思路
  如果两个链表都为空,返回空。如果两个链表一个为空,返回另一个链表的头结点。如果都不为空,创建一个新的头指针和尾指针,然后两个链表第一个元素比较,小的那个作为头指针和尾指针的指向的内容,然后分别对两个链表进行比较,小的值给尾指针,直到某一个链表结束,然后把另一个链表的剩下内容给尾指针。
图解
在这里插入图片描述
代码实现

struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2){
	struct ListNode* p1 = l1;
	struct ListNode* p2 = l2;
	if (p1 == NULL && p2 == NULL)
	{
		return NULL;
	}
	if (p1 == NULL)
	{
		return p2;
	}
	if (p1 == NULL || p2 == NULL)
	{
		return p1;
	}

	struct ListNode* head;
	struct ListNode* tail;

	if (p1->val <= p2->val)
	{
		head = p1;
		tail = p1;
		p1 = p1->next;
	}
	else
	{
		head = p2;
		tail = p2;
		p2 = p2->next;
	}

	while (p1 != NULL && p2 != NULL)
	{

		if (p1->val <= p2->val)
		{
			tail->next = p1;
			tail = tail->next;
			p1 = p1->next;
		}
		else
		{
			tail->next = p2;
			tail = tail->next;
			p2 = p2->next;
		}
	}

	if (p1 == NULL)
	{
		tail->next = p2;
	}
	else
	{
		tail->next = p1;
	}

	return head;
}

猜你喜欢

转载自blog.csdn.net/weixin_43580319/article/details/113402329