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;
}
}
List?{after the secondifstatement inerase. That looks unintentional; you have multiple statements indented after it. Try enclosing those statements in braces. (There are still errors, but that looks like it'd be a big problem. Looks like it unconditionally deletes the first entry.)