如何从未排序的链表中删除重复项

How to remove duplicates from an unsorted linked list

我当前的 remove_repeats 函数出现段错误。

remove_repeats函数:

void remove_repeats(node*& head){
    node* cursor = head;
    node* ptr;
    node* duplicate;

    while(cursor != NULL){
        ptr = cursor;
        while(ptr -> link != NULL){
            if(cursor -> data == ptr -> link -> data){
                duplicate = ptr -> link;
                ptr -> link = ptr -> link -> link;
                delete duplicate;
            }
            ptr = ptr -> link;
        }
        cursor = cursor -> link;
    }
}

主要内容:

int main(){
    int start, stop;
    int split;
    node* head = NULL;
    node *lesser;
    node * greater;

    start = time(NULL);
    build_list(head);
    stop = time(NULL);
    cout<<"Time to build list = "<<stop - start <<"seconds.\n";
    start = time(NULL);
    show_list(head);
    stop = time(NULL);
    cout<<"Time to print list = "<<stop - start<<"seconds.\n";
    cout<<"Size of the list = "<<size(head)<<endl;
    remove_repeats(head);



return 0;
}

主要是,build_list 函数构建了一个 linked 列表,其中包含 2000 个从 1 到 500 的随机整数。

show_list函数将linked列表的内容输出到屏幕。

大小函数 returns linked 列表中的节点数。

我认为问题是当最后一个节点数据重复并且之后没有节点分配给 ptr 的 link 时。可能不是这样,但如果是这样,我不确定如何处理。

此声明

ptr = ptr -> link;

应是前面 if 语句的 else 部分的子语句。给你。

void remove_repeats( node*&head )
{
    for ( node *cursor = head; cursor != nullptr ; cursor = cursor->link )
    {
        for ( node *ptr = cursor; ptr->link != nullptr; )
        {
            if ( cursor->data == ptr->link->data )
            {
                node *duplicate = ptr->link;
                ptr = ptr->link->link;
                delete duplicate;
            }
            else
            {
                ptr = ptr->link;
            }
        }
    }
}

另一种函数定义可以如下所示。

void remove_repeats( node*&head )
{
    for ( node *cursor = head; cursor != nullptr ; cursor = cursor->link )
    {
        for ( node **ptr = &cursor->next; *ptr != nullptr; )
        {
            if ( cursor->data == ( *ptr )->data )
            {
                node *duplicate = *ptr;
                *ptr = ( *ptr )->link;
                delete duplicate;
            }
            else
            {
                ptr = &( *ptr )->link;
            }
        }
    }
}

如果删除了linked-list的最后一个元素->p = p->link会导致空指针

while(ptr -> link != NULL){
            if(cursor -> data == ptr -> link -> data){
                ** delete ptr-> link (which is last element)
            }
            ptr = ptr -> link ( p will be null);
}