No matter what I do it just keeps giving me the numbers in the same way that I entered them. I would really appreciate some help on this, or advice.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
|
#include <iostream>
#include <string>
using namespace std;
struct ListNode
{
double number;
ListNode *next;
ListNode(double number1,ListNode *next1=NULL)
{
number=number1;
next=next1;
}
};
int main()
{
ListNode *head=NULL;
ListNode *current=NULL;
ListNode *tail=NULL;
ListNode *trail=NULL;
double nums;
for(int i=0;i<5;i++)
{
cout<<"Enter numbers: ";
cin>>nums;
if(i==0)
{
head=new ListNode(nums,NULL);
tail=head;
}
else
{
current=new ListNode(nums,NULL);
tail->next=current;
tail=current;
}
}
system("CLS");
current=head;
//This sort doesn't seem to work
//*****************************************
bool swapped=true;
while(swapped)
{
trail=head;
while(current->next!=NULL)
{
swapped = false;
if(current->number>current->next->number)
{
swapped=true;
if(head==current)
{
head=current->next;
current->next=head->next;
head->next=current;
trail=head;
}
else
{
trail->next=current->next;
current->next=trail->next->next;
trail->next->next=current;
}
current=current->next;
}
else if(head!=current)
{
trail=trail->next;
}
}
}
//*****************************************
tail=head;
while(tail!=NULL)
{
cout<<tail->number<<endl;
tail=tail->next;
}
return 0;
}
|
Thanks, but damn I think now it is an infinite loop..
Last edited on
I found 2 bugs in your logic
#49, swapped is initialized with false, so will not enter into while loop
#51, here current->next will be 0, so will not enter in the loop
If my understating is correct, the ListNode structure should contain tail, head pointers.