繁体   English   中英

删除重复链表

[英]Remove Duplicates linked list

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;
        }
    }
}

重要提示:节点对象的析构函数不允许删除 next 和 prev 指针后面的链接 object。

对于您的输入示例,它会导致 output 1->4->2->6->0 它的顺序并不完全准确,您想要 output,但每个数字在 output 中只存在一次。 它只添加重复号码的最后一次。 I don't really know, if you use C or C++, but because I prefer C++, I replaced the NULL with nullptr in the code. 如果对象不在使用 malloc 或新创建的 HEAP 上,则可以删除删除。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM