简体   繁体   中英

Adding element to a sorted list

i've got a problem with list, more specific - adding new element to it. This function is to add new element to a sorted list in proper place

ListEl* PushFrontsort(ListEl* head, ElType k)
{
    ListEl* x = (ListEl*) malloc(sizeof(ListEl));
    x->key = k;
    x->next = NULL;
    ListEl* y=head;
    ListEl* w=head;
    ListEl* new1 = (ListEl*) malloc(sizeof(ListEl));
    new1=head;
    w=w->next;
    if(head->key >= x->key)
    {
        x->next=head;
        new1=x;
    }
    else
    {
        while(w->key < x->key &&w->next)
        {
            y=w;
            w=w->next;
        }
        y->next=x;
        x->next=w;
    }
    return new1;
}

Type of the element is as following:

typedef struct ListEl {
    ElType key;
    struct ListEl *next;
} ListEl;

When I try to add new, random element using following instructions:

    int i;
    srand(time(NULL));
    ListEl* head = NULL;
    head = PushFront(head, rand()%100);
    for (i = 0; i < 20; i++)
        head = PushFrontsort(head, rand()%100);

not only sometimes doesn't it add 20 number and stops at 19, but very often program crashes. The whole problem is that I don't know what may cause this randomness of proper executing. If you can give me any advice to improve it, I'd be very grateful. Any help will be appreciated

The error only occurs when your second call for ListEl has a value for key larger than your first call. That's why the code was failing ~%50 of the time, because it all depends on which numbers were randomly called. As for "sometimes doesn't add 20 numbers and stop at 19", I'm not sure why this was happening, as I cannot reproduce this.

To fix your problem, from this answer, "If you need a pointer of a typedeffed type, declare an instance of one, but keep your typedefs to types so an not to mask levels of indirection."

So if you change your code to:

int i;
srand(time(NULL));
ListEl a = {0, NULL};
ListEl* head = &a; 
head = PushFront(head, rand()%100);
for (i = 0; i < 20; i++)
    head = PushFrontsort(head, rand()%100);

you should no longer have any issue. Also, it would probably be good form to change your typedef to:

typedef struct _ListEl {
    int key;
    struct _ListEl *next;
} ListEl;

So as to differentiate between the struct type and instance of struct type. To be honest, I'm not exactly sure why this needs to be done, so if someone more knowledgeable can edit/chime in, feel free.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM