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 ++,所以在代码中将NULL替换为nullptr。如果对象不在使用malloc或new创建的HEAP上,则可以删除删除。