我是c ++的新手,我想删除链表中的最大值。但是我收到了错误消息。这是删除最大值并返回删除值的函数。在运行该行"删除cur"时,我收到了错误消息。有人帮帮我!
int removeMax(Dnode*& list) {
Dnode *p = list->next;
Dnode *cur = list;
int max = list->info;
while (p != NULL) {
if (p->info > max) {
max = p->info;
cur = p;
}
p = p->next;
}
if(cur->back == NULL && cur != NULL){
Dnode *after = cur->next;
after->back = NULL;
delete cur;
}
else if(cur->next == NULL && cur != NULL){
Dnode *pre = cur->back;
pre->next = NULL;
delete cur;
}
else{
Dnode *pre = cur->back;
Dnode *after = cur->next;
pre->next = cur->back;
after->back = pre;
delete cur;
}
return max;
}
答案 0 :(得分:0)
错误可能是,而且很可能是,在其他地方,但至少最后的其他需要修复。而不是
pre->next = cur->back;
让前一个节点指向自身,它应该是
pre->next = after;
最后的其他内容也不会检查cur
是否有效。将整个部分包装成
if (cur != NULL) {
if (cur->back == NULL)
// ...
}
答案 1 :(得分:0)
您的list
未在功能中更新,removeMax
在删除最高元素(如果它是第一个列表)后崩溃。
// removing first element
if(cur->back == NULL && cur != NULL){
Dnode *after = cur->next;
list = after; // you need update your list
after->back = NULL;
delete cur;
}