c - keep on min max while insert sort - linked list -
i'm trying insert nodes linked list in sorted way, , keep on tail of list , head (which min , max)
this code:
void sortedinsert(automotor **head, automotor *new_car) { automotor* current; /* special case head end */ if (*head == null || (*head)->id >= new_car->id) { new_car->next = *head; *head = new_car; } else { /* locate node before point of insertion */ current = *head; while (current->next != null && current->next->id < new_car->id) { current = current->next; } int max = current->id; new_car->next = current->next; current->next = new_car; } printf("new car add m\n\n"); }
how can extract min & max (in o(1)) function(i print them)?
thank help
you add 2 parameters, old min , old max (pointers or refs), , update them each time insert.
edited per liona comment:
void sortedinsert(automotor **head, automotor *new_car, automotor **min, automotor **max) { automotor* current; /* special case head end */ if (*head == null || (*head)->id >= new_car->id) { new_car->next = *head; *head = new_car; *min = *head; } else { /* locate node before point of insertion */ current = *head; while (current->next != null && current->next->id < new_car->id) { current = current->next; } //int max = current->id; new_car->next = current->next; current->next = new_car; if ( current->next == null ) { *max = current; } } printf("new car add m\n\n"); }
Comments
Post a Comment