[英]Error with deleting several elements. Delete method. Single linked list
I made (with a little help) a single linked list, with C++, which sorts entered elements from least to greatest. 我使用C ++(在一点帮助下)制作了一个链接列表,该列表将输入的元素从最小到最大排序。 I want to delete several elements from the same value, but the Delete method I use seems to be able to delete only one, when the code seems to delete more. 我想从同一值中删除几个元素,但是当代码似乎删除了更多元素时,我使用的Delete方法似乎只能删除一个元素。 I try using a loop calling the Delete method in order to delete several elements, and when it deletes one it becomes a segmentation fault. 我尝试使用一个调用Delete方法的循环来删除几个元素,当它删除一个元素时,它将成为分段错误。 I'd appreciate some help. 我将不胜感激。 Thank you. 谢谢。
void List::Append(float time, char type, int cell, long id) {
// Create a new node
Node* newNode = new Node();
newNode->SetTime(time);
newNode->SetType(type);
newNode->SetCell(cell);
newNode->SetId(id);
newNode->SetNext(NULL);
// Create a temp pointer
Node *tmp = head;
if ( tmp ) {
if ( tmp->Time() < newNode->Time() ) {
newNode->SetNext(tmp);
head = newNode;
}
else {
// Nodes already present in the list
// Parse to end of list anytime the next data has lower value
while ( tmp->Next() && tmp->Next()->Time() >= newNode->Time() ) {
tmp = tmp->Next();
}
// Point the lower value node to the new node
Node* _next = tmp->Next();
tmp->SetNext(newNode);
newNode->SetNext(_next);
}
}
else {
// First node in the list
head = newNode;
}
} }
void List::Delete(long id) {
// Create a temp pointer
Node *tmp = head;
// No nodes
if ( tmp == NULL )
return;
// Last node of the list
if ( tmp->Next() == NULL ) {
delete tmp;
head = NULL;
}
else {
// Parse thru the nodes
Node *prev;
do {
if ( tmp->Id() == id ) break;
prev = tmp;
tmp = tmp->Next();
} while ( tmp != NULL );
// Adjust the pointers
prev->SetNext(tmp->Next());
// Delete the current node
delete tmp;
}
} }
in List::Delete code: 在列表中::删除代码:
if ( tmp->Id() == id ) break;<--------
if you break , the do{}while loop ends. 如果中断 ,则do {} while循环结束。 resulting in only 1 deletion. 仅导致1次删除。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.