Linked List Sort
Mar 5, 2017 at 3:55pm UTC  
I'm trying to sort the elements of a simple linked list, but the program crashed at the sort part;
1//c++ program 
#include <iostream> 
using  namespace  std;
struct  elem
{
    int  inf;
    elem *adr;
};
void  create_list(elem *&prim)
{
    cin>>prim->inf;
    prim->adr=0;
}
void  add_end(elem *&prim)
{elem* p,*q;
   p=new  elem;
   cin>>p->inf;
   p->adr=0;
   q=prim;
   while (q->adr!=0)
   q=q->adr;
   q->adr=p;
}
void  output(elem *&prim)
{elem* p;
 p=prim;
 while (p!=0)
 {cout<<p->inf<<" " ;
 p=p->adr;}}
int  main()
{ elem *prim,*i,*j;
prim=new  elem;
int  n,aux,k;
cin>>n;
create_list(prim);
for (k=1;k<n;k++)
add_end(prim);
for (i=prim;i->adr!=0;i=prim->adr)
for (j=prim->adr;j!=0;j=prim->adr)
{
    if (i->inf>j->inf)
    {
        aux=i->inf;
        i->inf=j->inf;
        j->inf=aux;
    }
}
output(prim);
return  0;
}
I just can't figure out where the bug is, I see nothing wrong with the loops. I'm desperately trying to work this out for about an hour.. Thanks in advance!
 
Mar 5, 2017 at 5:10pm UTC  
have you tested it up to the sort carefully?  If not, take them out and verify that output(prim) gives the original expected unsorted list without any crash. 
 
Mar 5, 2017 at 7:49pm UTC  
I did that, and it worked, it didn't give me any crash. The problem is inside the two for loops, but I don't know what.
 
Mar 5, 2017 at 8:20pm UTC  
Never mind, I found the bug. Thanks btw!
 
Topic archived. No new replies allowed.