每日一题(7) - 合并两个有序链表

题目来自剑指Offer

题目

每日一题(7) - 合并两个有序链表_第1张图片

代码

#include <iostream>
#include <assert.h>
using namespace std;

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

/*增+增 = 增,合并链表时要使用原链表空间*/
ListNode* Merge(ListNode* pFirstHead,ListNode* pSecHead)
{
	assert(pFirstHead != NULL && pFirstHead != NULL);
	ListNode* pCurFirst = pFirstHead;
	ListNode* pCurSec = pSecHead;
	ListNode* pCurNew = NULL;
	ListNode* pNewHead = NULL;

	//处理第一个结点
	if (pCurFirst->m_Data > pCurSec->m_Data)
	{
		pNewHead = pCurSec;
		pCurSec = pCurSec->m_pNext;
	}
	else
	{
		pNewHead = pCurFirst;
		pCurFirst = pCurFirst->m_pNext;
	}
	//标记新链表最后一个结点
	pCurNew = pNewHead;
	//处理后面的结点
	while (pCurFirst && pCurSec)
	{
		if (pCurFirst->m_Data > pCurSec->m_Data)
		{
			pCurNew->m_pNext = pCurSec;
			pCurNew = pCurNew->m_pNext;
			pCurSec = pCurSec->m_pNext;
		}
		else
		{
			pCurNew->m_pNext = pCurFirst;
			pCurNew = pCurNew->m_pNext;
			pCurFirst = pCurFirst->m_pNext;
		}
	}
	if (pCurFirst)
	{
		pCurNew->m_pNext = pCurFirst;
	}
	else
	{
		pCurNew->m_pNext = pCurSec;
	}
	return pNewHead;
}

void CreateList(ListNode** pHead,int nLen)//头指针使用指针的指针
{
	assert(*pHead == NULL && nLen > 0);
	ListNode* pCur = NULL;
	ListNode* pNewNode = NULL;
	for (int i = 0;i < nLen;i++)
	{
		pNewNode = new ListNode;
		cin>>pNewNode->m_Data;
		pNewNode->m_pNext = NULL;

		if (*pHead == NULL)
		{
			*pHead = pNewNode;
			pCur = *pHead;
		}
		else
		{
			pCur->m_pNext = pNewNode;
			pCur = pNewNode;
		}
	}
}

void PrintList(ListNode* pCurNode)
{
	assert(pCurNode != NULL);  
	while (pCurNode)  
	{  
		cout<<pCurNode->m_Data<<" ";  
		pCurNode = pCurNode->m_pNext;  
	}  
	cout<<endl;
}

int main()
{
	int nLen = 0;
	ListNode* pFirstHead = NULL;
	ListNode* pSecHead = NULL;
	ListNode* pNewHead = NULL;

	cout<<"please input node num: ";
	cin >> nLen;
	CreateList(&pFirstHead,nLen);//注意传参使用引用
	PrintList(pFirstHead);

	cout<<"please input node num: ";
	cin >> nLen;
	CreateList(&pSecHead,nLen);//注意传参使用引用
	PrintList(pSecHead);

	pNewHead = Merge(pFirstHead,pSecHead);
	PrintList(pNewHead);

	system("pause");
	return 1;
}

注意:

(1)需要一个头指针返回新链表

(2)注意游标的使用

递归的思路

代码

/*每次递归找到一个元素,并使用递归入口获得该元素的下一个元素*/
ListNode* Merge(ListNode* pCurFirst,ListNode* pCurSec)
{
	assert(pCurFirst != NULL || pCurSec != NULL);
	if (pCurFirst == NULL)
	{
		return pCurSec;
	}
	else if(pCurSec == NULL)
	{
		return pCurFirst;
	}
	else
	{
		ListNode* pMergeHead = NULL;
		if (pCurFirst->m_Data > pCurSec->m_Data)
		{
			pMergeHead = pCurSec;
			pMergeHead->m_pNext = Merge(pCurFirst,pCurSec->m_pNext);
		}
		else
		{
			pMergeHead = pCurFirst;
			pMergeHead->m_pNext = Merge(pCurFirst->m_pNext,pCurSec);
		}
		return pMergeHead;
	}
}


你可能感兴趣的:(每日一题(7) - 合并两个有序链表)