#include<iostream>
using namespace std;
struct ListNode
{
int m_nvalue;
ListNode* m_pNext;
};
void DeleteDulplication(ListNode** pHead)
{
if (pHead == nullptr || *pHead == nullptr)
return;
ListNode* pPreNode = nullptr;
ListNode* pNode = *pHead;
while (pNode != nullptr)
{
ListNode* pNext = pNode->m_pNext;
bool needDelete = false;
if (pNext != nullptr && pNext->m_nvalue == pNode->m_nvalue)
needDelete = true;
if (!needDelete)
{
pPreNode = pNode;
pNode = pNode->m_pNext;
}
else
{
int value = pNode->m_nvalue;
ListNode* pToBeDel = pNode;
while (pToBeDel != nullptr && pToBeDel->m_nvalue == value)
{
pNext = pToBeDel->m_pNext;
delete pToBeDel;
pToBeDel = nullptr;
pToBeDel = pNext;
}
//删除节点之后链接节点
if (pPreNode == nullptr)
*pHead = pNext;
else
pPreNode->m_pNext = pNext;
pNode = pNext;
}
}
}
int main()
{
ListNode* pHead = new ListNode();
pHead->m_nvalue = 5;
pHead->m_pNext = nullptr;
ListNode* a = new ListNode();
a->m_nvalue = 4;
a->m_pNext = nullptr;
pHead->m_pNext = a;
ListNode* b = new ListNode();
b->m_nvalue = 4;
b->m_pNext = nullptr;
a->m_pNext = b;
DeleteDulplication(&pHead);
ListNode* p = pHead;
while (p != nullptr)
{
cout << p->m_nvalue << " ";
p = p->m_pNext;
}
cin.get();
return 0;
}
剑指offer 面试题18(二) 删除链表中的重复节点
最新推荐文章于 2022-05-04 11:16:34 发布