简体   繁体   中英

c++ issue with bubble sort in linked list

i need some help in c++ bubble sort with linked list. I need to sort a list of int number like 55-10-50-33. I used this code

struct lista2{
    int val;
    lista2 *next;
};


void swap(int& x, int& y){
    int tmp ; tmp = x ; x = y ; y = tmp ;
}


ptr_lista2 sort (ptr_lista2 head){
    ptr_lista2 i,j;
    for(i=head; i->next!=NULL;i=i->next){
        for (j=head;j->next!=NULL;j=j->next){
            if(i->val < j->val) swap(i->val, j->val);
        }
    }
    return (head);
}

this code return 10-50-55-33. Why? Where is the error? I need 10-33-50-55!!

Thanks a lot to all!

It does not go to last element because the next pointer of last element is NULL ,

You need to make "j!=nullptr;"

You compare theese guys with themselves (it is not cause of your problem but it does not seem cool :D )

If you want to fix it, make "j=i->next;"

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