Answer the question
In order to leave comments, you need to log in
How to remove the first element of a singly linked list in c++?
As follows from the question - I had difficulty removing the first element, all others are removed without problems. The code with my comments is here marked with // ? at the location of the problem. I solved the problem using the "it works - don't touch" method, so I apologize in advance for what you can see there).
Tried the way:
if (curr->val == to_del) {
node* temp = curr;
curr = curr->next;
delete temp;
}
Answer the question
In order to leave comments, you need to log in
It is difficult with singly linked lists - you need to know the previous element in order to change its link to the next one through the element being deleted. You can either maintain 2 pointers to 2 adjacent elements, or look at the next element via next, as long as you have a pointer to the previous one.
Another separate problem with the removal of the first element, because there should not change the next link of the previous element, but the link to the beginning of the list. This problem can be solved in different ways. For example, instead of the head pointer, you can hold one element of the list without a value. Then the pointer to the beginning of the list will change just like any other. In fact, there will always be one dummy element in any list. This method is also preferred for dealing with doubly linked lists. Then the list, as it were, closes in a ring and it is not necessary to analyze separately either the case of the first or the case of the last element. I prefer another method - you can remember not the previous element, but a pointer-to-pointer, which will need to be changed.
node** prev_link = &head;
node* cur = head;
for (node* cur = head; cur != nullptr; cur = cur->next) {
if (cur->val == to_del) {
*prev_link = cur->next;
delete cur;
break;
}
prev_link = &cur->next;
}
You need two different versions of the code - for the first element and for the rest. Your code is correct for the first element. It remains to write for the rest.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question