leetcode合并有序链表

合并有序链表

题目链接:![https://leetcode.cn/problems/merge-two-sorted-lists/\]

有两种方法求解该题目:

  • 非递归方法
  • 递归方法

非递归方法

使用非递归方法,关键在于记录已经合并好的链表的尾指针。

cpp 复制代码
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
	if (list1 == nullptr)
		return list2;
	else if (list2 == nullptr)
		return list1;

	ListNode* p = list1;
	ListNode* q = list2;
	ListNode* head; //已经合并好的链表的表头
	ListNode* r = new ListNode(); //已经合并好的链表的表尾
	head = r;

	while (p && q)
	{
		if (p->val < q->val)
		{
			r->next = p;
			p = p->next;
		}
		else
		{
			r->next = q;
			q = q->next;
		}

		r = r->next;
	}

	if (p == nullptr)
		r->next = q;
	else
		r->next = p;

	return head->next;
}

这里使用了哨兵节点,用于统一头部数据的比较,这使我们不需要对两个链表的头节点进行特殊处理,可以直接在循环中处理。

递归方法

c 复制代码
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
    if(l1==NULL)
        return l2;
    if(l2==NULL)
        return l1;
    if(l1->val < l2->val){
        l1->next = mergeTwoLists(l1->next,l2);
        return l1;
    }else{
        l2->next = mergeTwoLists(l1,l2->next);
        return l2;
    }
}
相关推荐
琢磨先生David6 天前
Day1:基础入门·两数之和(LeetCode 1)
数据结构·算法·leetcode
超级大福宝6 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode
Charlie_lll6 天前
力扣解题-88. 合并两个有序数组
后端·算法·leetcode
菜鸡儿齐6 天前
leetcode-最小栈
java·算法·leetcode
Frostnova丶6 天前
LeetCode 1356. 根据数字二进制下1的数目排序
数据结构·算法·leetcode
郝学胜-神的一滴6 天前
深入理解链表:从基础到实践
开发语言·数据结构·c++·算法·链表·架构
im_AMBER6 天前
Leetcode 127 删除有序数组中的重复项 | 删除有序数组中的重复项 II
数据结构·学习·算法·leetcode
样例过了就是过了6 天前
LeetCode热题100 环形链表 II
数据结构·算法·leetcode·链表
tyb3333336 天前
leetcode:吃苹果和队列
算法·leetcode·职场和发展
网小鱼的学习笔记6 天前
leetcode876:链表的中间结点
数据结构·链表