常见单链表题型(五)合并两个有序链表

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_44759710/article/details/102545841

题目要求

将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的

示例:
输入:1->2->4 , 1->3->4
输出:1->1->2->3->4->4

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */

解题思路

方法:
给两个指针 p1,p2 ,分别指向两个链表头元素并进行比较,将较小的放入新链表,对应原链表指针后移,直到一方指向空,另一个链表剩下部分直接插入,有一个链表为空时,应该直接返回另一个链表

解题演示

输入:1->2->4 , 1->3->4
输出:1->1->2->3->4->4

过程显示:

  • 1->2->4 记作左, 1->3->4 记作右
  • 左(1)>= 右(1),所以新链表头为 右(1),右 = 右->next
  • 继续进行比较,左(1) < 右(3),所以有 右(1)->next = 左(1),一直到右(4)被读入链表中,右为空,左边剩余链表直接读入新链表
  • 最后得到结果应为右(1)-> 左(1)-> 2 -> 3 -> 右(4)-> 左(4)

解题代码

递归写法:

struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2)
{
	struct ListNode* newNode;
	if (!l1)
		return l2;
	if (!l2)
		return l1;
	if (l1->val < l2->val)
	{
		newNode = l1;
		newNode->next = mergeTwoLists(l1->next, l2);
	}
	else
	{
		newNode = l2;
		newNode->next = mergeTwoLists(l1, l2->next);
	}
	return newNode;
}

非递归写法:

struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2)
{
	if (l1 == NULL)
		return l2;
	if (l2 == NULL)
		return l1;
	struct ListNode* newNode;
	struct ListNode* tail;
	if (l1->val < l2->val)
	{
		newNode = l1;
		l1 = l1->next;
	}
	else
	{
		newNode = l2;
		l2 = l2->next;
	}
	tail = newNode;
	while (l1 && l2)
	{
		if (l1->val < l2->val)
		{
			tail->next = l1;
			l1 = l1->next;
		}
		else
		{
			tail->next = l2;
			l2 = l2->next;
		}
		tail = tail->next;
	}
	if (l1)
		tail->next = l1;
	else if (l2)
		tail->next = l2;
	return newNode;
}

猜你喜欢

转载自blog.csdn.net/qq_44759710/article/details/102545841