【发布时间】:2020-06-09 16:02:30
【问题描述】:
我当前的 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;
}
在main中,build_list函数构建了一个2000个随机整数的链表,范围从1到500。
show_list 函数将链表的内容输出到屏幕上。
size 函数返回链表中的节点数。
我认为问题是当最后一个节点数据是重复的并且之后没有节点分配给 ptr 的链接。可能不是这样,但如果是这样,我不知道如何处理。
【问题讨论】:
-
您的内部
while循环在删除重复项后执行ptr = ptr->link;后未检查ptr是否变为空。 -
你的链表一开始有重复的值吗?我问是因为具有删除重复功能意味着您要避免重复。如果是这种情况,请考虑改用排序数据结构。
-
@John 也许这只是一个练习。
-
@0x499602D2 可能是,但除非我问 OP,否则无法知道。
-
@John 这是学校的实验室。应该有重复,这就是为什么列表中有 2000 个点,但只有一个节点的数据可能是 1 到 500 之间的整数
标签: c++ function struct linked-list singly-linked-list