简体   繁体   English

链表中冒泡排序的C ++问题

[英]c++ issue with bubble sort in linked list

i need some help in c++ bubble sort with linked list. 我需要一些C ++气泡排序和链表帮助。 I need to sort a list of int number like 55-10-50-33. 我需要对整数编号列表进行排序,例如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. 此代码返回10-50-55-33。 Why? 为什么? Where is the error? 错误在哪里? I need 10-33-50-55!! 我需要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 , 它不会转到最后一个元素,因为最后一个元素的下一个指针为NULL,

You need to make "j!=nullptr;" 您需要使“ j!= nullptr;”

You compare theese guys with themselves (it is not cause of your problem but it does not seem cool :D ) 您将这些家伙与自己进行比较(这不是问题的根源,但看起来并不酷:D)

If you want to fix it, make "j=i->next;" 如果要修复它,请使“ j = i-> next;”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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