### Sort function for Linked list program

I'm having trouble getting my sort function to work,

 ``12345678910111213141516171819202122232425262728293031323334`` ``````void Linkedlist::sort(int num) { node *q; node *a; int input=num; a = new node; a->data=input; a->link=NULL; q=head; while(q->link !=NULL) { int temp=0; temp = q->link->data - input; if(temp>0) { a->link=q->link; q->link=a; break; } } q=q->link; if (q->link = NULL) { q->link = a; } }``````

I get a crash and I've narrowed it down to the last if statement. Also this function is meant to handle new members after 1 member has been added. Where am I going wrong?
What sorting algorithm are you trying to implement?

Line 29:
- You assign q->link to NULL then line 32 you try to dereference a null pointer
- Either line 27 or 29 could crash the program as soon as line 32 is executed - look at the condition of your while loop
I was trying to make it sort so that if node *a was less than the element node *q was pointing to, it would point a->link=q->link and q->link=a and swap the a and q's positions.
So I realized my function was pretty screwy, heres my new attempt, but it is still crashing...

 ``123456789101112131415161718192021222324252627282930`` ``````void Linkedlist::sort(int num) { node *q; node *a; int input=num; a = new node; a->data=input; a->link=NULL; q=head; if(input < q->data) { a->link=q; } else { int temp=0; temp = q->link->data - input; if(temp>0) { a->link=q->link; q->link=a; } } }``````
Line 21, how are you making sure that `q->link` is not a null reference?
okay I almost fixed it!

 ``12345678910111213141516171819202122232425262728293031323334353637383940`` ``````void Linkedlist::sort(int num) { node *q; node *a; int input=num; a = new node; a->data=input; a->link=NULL; q=head; if(input < q->data) { a->link=q; a=head; } else { int temp=0; if(q->link!=NULL) { temp = q->link->data - input; if(temp>0) { a->link=q->link; q->link=a; q=head; } } else { q->link=a; a->link=NULL; q=head; } } }``````

Okay so now I have it working, but im only getting certain numbers on the output:

Enter 10 numbers, or -1 to quit:
6
3
8
7
1
9
8
4
3
2
Linkedlist Members in sorted order: 6 7 8
Press any key to continue . . .
You only did one set of operations on the list which is why you obtained the numbers you get. What does your insert function look like?
I fixed it!
thanks for the help but i got a friend to help me out

 ``12345678910111213141516171819202122232425262728293031323334353637383940414243444546`` ``````void Linkedlist::sort(int num) { node *q; node *a; int input=num; a = new node; a->data=input; a->link=NULL; q=head; if(a->data < q->data) { a->link=q; head=a; } else { while(q!=NULL) { if(q->link!=NULL) { int temp=0; temp = q->link->data - input; if(temp>0) { a->link=q->link; q->link=a; break; } } else { q->link=a; a->link=NULL; break; } q=q->link; } } }``````
Topic archived. No new replies allowed.