[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: help with C algorythm (find unique value in an array) could you please make changes



On Mon, Jan 22, 2007 at 11:42:32AM -0600, Ron Johnson wrote:
> On 01/22/07 11:22, Jon Dowland wrote:
> > On Mon, Jan 22, 2007 at 10:30:29AM +0000, Jon Dowland wrote:
> [snip]
> >     /* populate the unique list */
> >     for(i = 1; i < argc; ++i) {
> >         int val = atoi(argv[i]);
> >         if(!in_list(val, list)) {
> >             list = add_to_list(val, list);
> >         }
> >     }
>
> Unless I'm misreading, this would not scale well *at all*.

No you're quite right, not least since my insertion routine
traverses the whole list on each call. I didn't write this
for speed of execution, merely speed of writing it :)

This would improve insertions (but obviously not the in_list
test):

struct node * add_to_list(const int val, struct node *list) {
    newlist = malloc(sizeof(struct node));
    if(!newlist) {
        fprintf(stderr,"error allocating list node\n");
        exit(1);
    }
    newlist->val = val;
    newlist->next = list;
    return newlist;
}


-- 
Jon Dowland



Reply to: