简体   繁体   中英

Problems ordering a linked list in C

I got issues trying to order a linked list from its min to its max, the code is:

struct nodo *orderList (struct nodo *p) {

struct nodo *head=p;
struct nodo *min=p;
int *tmp=NULL;

while (min != NULL) {
    p = min;
    // p = p->succ (not necessary i think)
            while (p != NULL) {
                    if (p->info < min->info) {
                            tmp = &min->info;
                            min->info = p->info;
                            p->info = *tmp;
                    }
                p=p->succ;
            }
        min=min->succ;
}
return head;
}

The output i get (i use a tested function to create a list with n nodes from input) :

Number of elements: 4
insert 4 positive numbers: 
4
3
2
1

1 ->  1 ->  1 ->  1 -> 

By using a int * , when you swap the info field, you refer to the modified field.

You should declare tmp as:

int tmp;

and adjust your swap code accordingly.

In this way you would copy the value of min->info before changing it.

This code does not swap the data

tmp = &min->info;
min->info = p->info;
p->info = *tmp;

The third line simply moves the data back to where it was, since min->info now contains p->info .

You need to swap like this

int tmp = min->info;
min->info = p->info;
p->info = tmp;

assuming the data type is int as you didn't post the struct .

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