剑指offer ——删除链表中重复的节点
解法:
在重新定义链表指针域的同时, 使用 delete 释放了已删除节点的内存空间。
class Solution {
public:
ListNode* deleteDuplication(ListNode* pHead)
{
if (pHead == nullptr || pHead->next == nullptr) { //平凡列表无重复,确保列表有两个节点
return pHead;
}
ListNode* pSentinel = new ListNode(-1);// 构造一个哨兵节点
pSentinel->next = pHead;
ListNode* pNode = pHead;
ListNode* pPreNode = pSentinel;
while (pNode != nullptr && pNode->next != nullptr) {
ListNode* pNext = pNode->next;
if (pNode->val == pNext->val) {
int value = pNode->val;
delete pNode;
pNode = nullptr;
while (pNext->val == value && pNext != nullptr) {
pNext = pNext->next;
}
pPreNode->next = pNext;
pNode = pNext;
}
else {
pPreNode = pNode;
pNode = pNext;
}
}
return pSentinel->next;
}
};