牛客网JZ25合并两个排序的链表

描述:

在这里插入图片描述

示例:

在这里插入图片描述
在这里插入图片描述

代码:

方法一:

正常比较两个链表的头节点,然后插入新链表的尾部

class Solution {
public:
	ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
	{
		if (nullptr == pHead1) return pHead2;
		if (nullptr == pHead2) return pHead1;
		ListNode* new_head = nullptr;
		ListNode* new_tail = nullptr;
		while (pHead1 && pHead2) {
			ListNode* p = pHead1->val < pHead2->val ? pHead1 : pHead2;
			if (p == pHead1) pHead1 = pHead1->next;
			else pHead2 = pHead2->next;
			if (nullptr == new_head) {
				new_head = p;
				new_tail = p;
			}
			else {
				new_tail->next = p;
				new_tail = p;
			}
		}
		if (nullptr == pHead1) new_tail->next = pHead2;
		else if (nullptr == pHead2) new_tail->next = pHead1;
		return new_head;
	}
};

方法二:递归

比较两个链表的头结点,然后删除头部插入新链表的尾部,然后再传入函数中,,,

class Solution {
public:
	ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
	{
		if (nullptr == pHead1) return pHead2;
		if (nullptr == pHead2) return pHead1;
		ListNode* new_head = nullptr;
		if (pHead1->val < pHead2->val) {
			new_head = pHead1;
			pHead1 = pHead1->next;
		}
		else {
			new_head = pHead2;
			pHead2 = pHead2->next;
		}
		new_head->next = Merge(pHead1, pHead2);
		return new_head;
	}
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值