On Monday 19 June 2006 13:55, Verdi March wrote:
int insertion_sort(IntList *ilist, IntStruct *is) { IntStruct **isp; for (isp = &ilist->head; *isp; isp = &((*isp)->next)) { if (is->i < (*isp)->i) { is->next = *isp; break; } else if (is->i == (*isp)->i) { /* return FALSE; */ return 0; } }
*isp = is;
OK, I was wrong, it works. The layers of double indirection threw me. I think it's a very poor way of programming, I don't like it at all Here's how I would do it, which I think is much easier to read #include <stdio.h> #include <stdlib.h> typedef struct _int_struct { int i; struct _int_struct *next; } IntStruct; typedef struct _int_list { IntStruct *head; } IntList; void insert(IntList *ilist, int i); void insertion_sort(IntList *ilist, IntStruct *is); int main() { IntStruct *is; IntList ilist; ilist.head = NULL; insert(&ilist, 500); insert(&ilist, 100); insert(&ilist, 600); printf("ilist: "); for (is = ilist.head; is != NULL; is = is->next) printf("%d ", is->i); printf("\n"); return 0; } void insert(IntList *ilist, int i) { IntStruct *is = (IntStruct *) calloc(1, sizeof(IntStruct)); /* line 36 */ is->i = i; is->next = NULL; insertion_sort(ilist, is); return; } void insertion_sort(IntList *ilist, IntStruct *is) { IntStruct *isp; if(ilist->head == NULL){ ilist->head = is; return; } if(is->i <= ilist->head->i){ is->next = ilist->head; ilist->head = is; return; } for (isp = ilist->head; isp->next != NULL; isp = isp->next) if (is->i <= isp->next->i) { is->next = isp->next; isp->next = is; return; } isp->next = is; }