删除重复项链表

Remove Duplicates linked list

本文关键字:链表 项链 删除      更新时间:2023-10-16
void RemoveDuplicates(Slist& l)
{
if (l.head == NULL) {
return;
}
Node* cur = l.head;
while (cur != NULL && cur->next != NULL) {
Node* prev = cur;
Node* temp = cur->next;
while (temp != NULL) {
if (temp->data == cur->data) {
prev->next = temp->next;
cur->next = prev->next;
temp = prev->next;
}
else {
prev = prev->next;
temp = temp->next;
}
}
cur = cur->next;
}
}

嗨,我想从链表中删除重复项(0 为 NULL(

input:  1->2->2->4->2->6->0 
outPut: 1->2->4->6->0

运行程序后的结果是:

1->2->6

我错在哪里?请帮助我

这是我对您的问题的解决方案:

bool alreadyExist(Node head)
{
Node cur = head;
while(cur.next != nullptr)
{
if(cur.next->data == head.data) {
return true;
}
cur = *cur.next;
}
return false;
}
void RemoveDuplicates(Slist& l)
{
if (l.head == nullptr) {
return;
}
Node* head = l.head;
Node* curPtr = l.head->next;
while(curPtr != nullptr)
{
if(alreadyExist(*curPtr) == false)
{
head->next = curPtr;
head->next->prev = head;
head = head->next;
curPtr = curPtr->next;
}
else
{
Node* backup = curPtr;
curPtr = curPtr->next;
// delete duplicate elements from the heap,
// if the nodes were allocated with new, malloc or something else
// to avoid memory leak. Remove this, if no memory was allocated
delete backup;
}
}
}

重要提示:不允许节点对象的析构函数删除下一个和上一个指针后面的链接对象。

对于您的输入示例,它会在输出1->4->2->6->0中产生结果。它不完全精确的顺序,你想要作为输出,但每个数字在输出中只存在一次。它只添加重复号码的最后一次。 我真的不知道,如果你使用 C 还是C++,但因为我更喜欢C++,所以我在代码中用 nullptr 替换了 NULL。如果对象不在使用 malloc 或 new 创建的堆上,则可以删除删除。