我不知道我的代码有什么问题。另外,如何删除链表中的节点。
for( IntNode* i = head; i != 0; i = i->next ) {
IntNode* prev = i;
for( IntNode* j = i->next; j != 0; j = j->next ) {
if( j->data == i->data ) {
IntNode* temp = j;
prev->next = j->next;
delete temp;
}
prev = prev->next;
}
}
答案 0 :(得分:0)
我会在黑暗中拍摄并说你有记忆困扰吗?
我认为这是因为如果你删除一个节点,你会留下j
的悬空记忆。
您需要具备以下条件:
IntNode* temp =
prev->next = j->next;
j = j->next;
delete temp;
您需要修改for
循环。请考虑以下事项:
IntNode *j = i->next;
while (j != 0) {
if( j->data == i->data ) {
//As above
} else {
j = j->next;
}
prev = prev->next;
}
答案 1 :(得分:0)
你忘了设置'j'。
for (IntNode* i = head; i != 0; i = i->next) {
IntNode* prev = i;
for (IntNode* j = i->next; j != 0; j = j->next) {
if (j->data == i->data) {
IntNode* temp = j;
prev->next = j->next;
j = prev;
delete temp;
}
else
{
prev = prev->next;
}
}
}