面试题整理13 合并排序链表去重

题目:合并两个排序链表,去掉重复元素

struct ListNode
{
	int m_nValue;
	ListNode* m_pNext;
};
using namespace std;

ListNode* MergeLists(ListNode* pHead1,ListNode* pHead2)
{
	if(pHead1 == NULL && pHead2 == NULL)
		return NULL;
	if(pHead1 == NULL && pHead2 != NULL)
		return pHead2;
	if(pHead1 != NULL && pHead2 == NULL)
		return pHead1;
	ListNode* newListHead = pHead1;
	if( pHead1->m_nValue > pHead2->m_nValue )
	{
		swap(pHead1,pHead2);
	}
	while( pHead1!= NULL && pHead2 != NULL)
	{
		while( pHead1 != NULL && pHead1->m_pNext != NULL && pHead1->m_pNext->m_nValue < pHead2->m_nValue)
		{
			//qu chong 
			while( pHead1->m_pNext != NULL && pHead1->m_nValue == pHead1->m_pNext->m_nValue)
			{
				pHead1->m_pNext = pHead1->m_pNext->m_pNext;
			}

			if( pHead1->m_pNext->m_nValue < pHead2->m_nValue)
			{
				pHead1 = pHead1->m_pNext;
			}
		}

		if( pHead1!=NULL && pHead1->m_nValue == pHead2->m_nValue)
		{
			while( pHead2 != NULL && pHead2->m_nValue == pHead1->m_nValue )
			{
				pHead2 = pHead2->m_pNext;
			}
		}
		ListNode* tempNode = pHead1->m_pNext;
		pHead1->m_pNext = pHead2;
		pHead1 = pHead2;
		pHead2 = tempNode;
	}
	return newListHead;
}

你可能感兴趣的:(C++,算法,合并排序链表)