问题
I am working on iterative delete function that deletes node from a linked list, I think that the code is supposed to work fine, it traverses through the list, finds the needed node, points the head to the next node and deletes the current, but when I test run it I get infinite loop, could you please help me to pinpoint the error, here is the function:
typedef struct E_Type * List;
struct E_Type
{
int data;
struct E_Type* next;
};
the function:
bool erase(List & l, int data){
List head = l;
if (l != 0){
for(List current = head; current; current = current->next){
if ( current->data == data )
head = current->next;
delete current;
return true;
}
}
return false;
}
the test program:
int main()
{
List l = 0;
cout << boolalpha << l->data << "went well? "<< (insert(l,73)) << endl;
cout << boolalpha << l->data << "went well? "<< (insert(l,24)) << endl;
print(cout,l);
cout << boolalpha << "Is deleted 24? "<<(erase(l,24)) << endl;
cout << boolalpha << "Is deleted 35? "<<(erase(l,35)) << endl;
print(cout,l);
cout << endl;
return 0;
}
the insert:
bool insert(List & l, int data)
{
List current = l;
while(current != 0) {
if (current->data == data)
return false;
current = current->next;
}
if (l == 0 || l->data > data){
List new_list = new E_Type;
new_list->data = data;
new_list->next = l;
l = new_list;
return true;
}
else if(l->data < data){
insert(l->next, data);
return true;
}
}
回答1:
As Andreas Brinck already points out, you need to update the 'previous' link as well. However, you don't need a dedicated variable for this, just use a pointer to a pointer:
bool erase(List & l, int data){
List *it = &l;
while ( *it ) {
if ( (*it)->data == data ) {
List next = (*it)->next;
delete *it;
*it = next;
return true;
}
it = &(*it)->next;
}
return false;
}
This also takes care of handling all the "special cases" such as deleting from an empty list, deleting the first element in the list or deleting the last element in the list.
回答2:
You need to keep track of the previous node as well in your for loop and do something like:
prev->next = current->next;
delete current;
You'll also need to handle the case where the deleted element is the first element of the list, in this case you need to set l
to l->next
bool erase(List & l, int data){
if (l != 0){
for(List current = head, prev = 0; current; prev = current, current = current->next){
if ( current->data == data )
{
if (prev)
{
prev->next = current->next;
}
else
{
l = current->next;
}
delete current;
return true;
}
}
return false;
}
Your first erase is probably creating a circular list right now.
回答3:
We may need to see your insert method as well.
Is it possible that
current == current->next
If so that could cause the infinite loop.
来源:https://stackoverflow.com/questions/13840591/delete-node-from-linked-list