So, i have a linked list with 47 thousand nods. each node has year month and day. I want to remove nodes that dont fit into [month initial, month final]. So if i chose the month initial as 3 and the final as 8, for exemple, i want to remove the ones that dont fit wichever is the year and day.
LISTAPAISES *Filtra_month(LISTAPAISES * head, int month_init, int month_final) {
LISTAPAISES *aux=NULL, *elim=NULL, *aux2=NULL;
aux=head;
while(aux !=NULL){
if(aux->country.month>month_final || aux->country.month<month_init){
elim=aux;
aux=aux->next;
free(elim);
}
else{
if(aux2==NULL){
aux2=aux;
}
aux=aux->next;
}
}
return aux2;
}
This seems no get the nods that i want, but instead of clearing them it just puts random numbers in. Any sugestions? Thanks in advance.
Say you have a linked-list A->B->C
. When you're freeing B
node, the previous node A
, by your code, it still points to the old memory location B
and not the new node C
. The random numbers, if not segmentation faults, is just garbage memory where B
used to be being read.
Fix it by having two pointers, aux
, and ahead
. The aux
pointer stays behind ahead
one node, and if ahead
passes the failing constrain, free
it, assign ahead
to ahead->next
, and update aux
accordingly.
LISTAPAISES* ahead = NULL;
aux = head;
// Special case if head passes the failing constain
if(head != NULL && (head->country.month>month_final || head->country.month<month_init)){
aux = aux->next;
free(head);
head = aux;
}
if(aux != NULL){
ahead = aux->next;
}
while(ahead != NULL){
if(ahead->country.month>month_final || ahead->country.month<month_init){
// Create a tmp pointer to hold the node after 'ahead'
LISTAPAISES* tmp = ahead->next;
free(ahead);
// Reassign the previous pointer to now point to `tmp`
aux->next = tmp;
// Update 'ahead' to be 'tmp' for the next iteration
ahead = tmp;
}
else{
ahead = ahead->next;
aux = aux->next;
}
}
return head;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.