使用重复的相同值删除已排序链接列表中的重复值

时间:2015-10-13 04:58:10

标签: c++ data-structures linked-list

在删除重复次数超过1次的值后,我在打印已排序的链接列表时遇到问题。

代码:

4
6
1 2 2 3 3 4
7
1 1 1 1 1 1 1
5
2 3 3 4 6
1
10

这会删除多次出现的值,但除此之外它不起作用,我无法找到原因。

测试用例:

例如:如果INPUT是这样的:

1 2 3 4
1
2 3 4 6
10

然后它应该有这样的OUTPUT:

1 2 3 4
1 1 1 1
2 3 4 6
10

但我的输出是:

{{1}}

3 个答案:

答案 0 :(得分:1)

这是一种可能的方法。基本思路是遍历列表,只要有下一个节点,数据匹配就会剪切列表中的下一个节点。我添加了一个DeleteNode()辅助函数,它释放一个节点并返回它的旧next指针。此实用程序在其他上下文中很有用。

Node* DeleteNode(Node *node)
{
    Node *ptr = node->next;
    delete node; // This is C++, you might need free() instead
    return ptr;
}

Node* RemoveDuplicates(Node *list)
{
    Node *node = list;
    while (node) {
        while (node->next && (node->data == node->next->data)) {
            node->next = DeleteNode(node->next);
        }
        node = node->next;
    }
    return list;
}

答案 1 :(得分:1)

当释放cur时,无法访问。 你可以这样做:

Node* RemoveDuplicates(Node *head)
{
    if(head==NULL){
        return NULL;
    }
    Node *prev,*cur;
    cur=head;
    while(cur->next!=NULL)
    {
        prev = cur;
        cur = cur->next;
        if(prev->data == cur->data)
        {
            prev->next = cur->next;
            free(cur);
            cur = prev;
        }
    }
    return head;
}

答案 2 :(得分:0)

以下是您的代码的改进版本,我相信它会毫无问题地运行。我在开头添加了NULL检查,并修改了算法以正确处理重复项:

Node* RemoveDuplicates(Node *head)
{
    if (head == NULL)         // return NULL in case of empty list
        return NULL;

    if (head->next == NULL)   // return the head in case of list with only one element
        return head;

    Node *prev,*cur;
    prev = head;
    cur  = head->next;

    while (cur != NULL)
    {
        if (prev->data != cur->data) {
            prev->next = cur;
            prev = cur;    
            cur = cur->next;
        }
        else {
            Node* temp = cur;
            cur = cur->next;
            free(temp);       // delete a duplicate node
        }
    }

    prev->next = NULL;        // NULL-terminate the modified list

    return head;
}