50.删除链表中重复的结点
题目内容:
代码及思路:
以图示的链表为例,最后结点值为2的指向结点值为5的结点。
#include<iostream>
#include<unordered_map>
#include<deque>
#include<string>
using namespace std;
struct ListNode
{
int val;
ListNode* next;
};
class Solution
{
public:
ListNode* buildList()
{
ListNode* p1 = nullptr;
ListNode* p2 = nullptr;
ListNode* phead = nullptr;
int num;
char ch;
do
{
cin >> num;
p1 = new ListNode;
p1->val = num;
if (phead == nullptr)
{
phead = p1;
}
else
{
p2->next = p1;
}
p2 = p1;
cin.get(ch);
} while (ch == ',');
if (phead == nullptr)
return nullptr;
p2->next = nullptr;
return phead;
}
ListNode* deleteDuplication(ListNode* pHead)
{
if (pHead == nullptr)
return nullptr;
ListNode* pNode = pHead;
//设置前一个结点以作删除时连接准备
ListNode* pPreNode = nullptr;
while (pNode != nullptr)
{
bool needDelete = false; //设置一个删除判断变量
//若当前结点值等于下一个结点值,那么就是重复的结点,都要被删除
if (pNode->next&&pNode->next->val == pNode->val)
needDelete = true;
if (!needDelete)
{
pPreNode = pNode;
pNode = pNode->next;
}
else //出现重复结点
{
ListNode* pNext = nullptr;
//重复结点的值
int value = pNode->val;
while (pNode != nullptr&&pNode->val == value)
{
pNext = pNode->next;
delete pNode;
pNode = pNext;
}
if (pPreNode == nullptr) //要保证pPreNode与下一个没有重复的结点连接在一起
pHead = pNext;
else
pPreNode->next = pNext;
}
}
return pHead;
}
};
void main()
{
Solution* object = new Solution;
ListNode* phead = object->buildList();
ListNode* p1 = nullptr;
p1 = object->deleteDuplication(phead);
while (p1 != nullptr)
{
cout << p1->val << endl;
p1 = p1->next;
}
}