Функция del_node
имеет две проблемы:
1) Невозможно удалить узел, когда список содержит ровно 1 элемент
2) Удаляет неправильный элемент
Итак, давайте начнем с номера 1 и посмотрим на код:
if(head==nullptr)
{
cout<<"no element to delete.!";
exit(0);
}
else
{
while(temp_del->next!=nullptr)
Предположим, что список содержит точно один элемент.Это означает:
a) head
равно не NULL
b) head->next
и, следовательно, temp_del->next
равно NULL
, поэтому while(temp_del->next!=nullptr)
приведет к ложному результату, т.е. цикл не будет выполнен.Общий результат состоит в том, что код ничего не делает.
Теперь для числа 2. Код:
if(temp_del->next->data==val_del)
{
temp_del->next=temp_del->next->next; // You want to delete temp_del->next
// but here you change it
delete temp_del->next->next; // so here you delete the wrong node
// there is also an extra ->next
}
Вам нужна временная переменная для хранения указателя на узел, который вы хотите удалить.
Вы, вероятно, хотите, чтобы код был:
int del_node(int val_del)
{
// Delete elements in the front
while (head!=nullptr && head->data==val_del)
{
node* node_to_delete = head;
head = head->next;
delete node_to_delete;
// return 0; Uncomment if you only want one delete per function call
}
if(head==nullptr) return 0;
// Delete elements not in the front
node* temp_del=head;
while(temp_del->next!=nullptr)
{
if (temp_del->next->data==val_del)
{
node* node_to_delete = temp_del->next;
temp_del->next = temp_del->next->next;
delete node_to_delete;
// return 0; Uncomment if you only want one delete per function call
}
temp_del=temp_del->next;
}
return 0;
}