您的位置:首页 > 职场人生

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

2014-03-08 09:07 375 查看
题目:合并两个排序链表,去掉重复元素

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: