我当前的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函数构建一个链表,该链表包含2000个随机整数,范围从1到500。
show_list函数将链接列表的内容输出到屏幕。
size函数返回链表中节点的数量。
我认为问题在于最后一个节点数据是重复数据,而之后没有节点可分配给ptr的链接。情况可能并非如此,但是如果是这样,我不确定该如何处理。
这个说法
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;
}
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句