《剑指offer》面试题 25:合并两个排序的链表(C++实现)

题目

输入两个递增排序的链表,合并这两个链表并使新链表中的结点仍然是按照递增排序的。

代码

#pragma once

struct ListNode
{
	int m_nValue;
	ListNode* m_pNext;
};

/**
 * 递归 注意递归结束条件
 */

ListNode* mergeList(ListNode* pHead1, ListNode* pHead2)
{
	if (pHead1 == nullptr)
		return pHead2;
	if (pHead2 == nullptr)
		return pHead1;

	ListNode* pMergedHead = nullptr;
	if (pHead1->m_nValue < pHead2->m_nValue)
	{
		pMergedHead = pHead1;
		pMergedHead->m_pNext = mergeList(pHead1->m_pNext, pHead2);
	}
	else
	{
		pMergedHead = pHead2;
		pMergedHead->m_pNext = mergeList(pHead1, pHead2->m_pNext);
	}

	return pMergedHead;
}

 

你可能感兴趣的:(剑值offer)