我(在一点帮助下)用 C++ 制作了一个单链表,它将输入的元素从最小到最大排序。我想从同一个值中删除几个元素,但是当代码似乎删除更多时,我使用的 Delete 方法似乎只能删除一个。我尝试使用一个调用 Delete 方法的循环来删除几个元素,当它删除一个元素时,它就变成了分段错误。我会很感激一些帮助。谢谢你。
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;
}
}