Linked List Sort

I'm trying to sort the elements of a simple linked list, but the program crashed at the sort part;

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
//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!
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.

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.
Never mind, I found the bug. Thanks btw!
Topic archived. No new replies allowed.