void stack:: pushsort(int item)
{
node *t=new node;
cout<<"your function is calling"<<endl;
if(head == NULL)
{ cout<<"test"<<endl;
t->next=head;
t->data=item;
head=t;
}
elseif(item <= head->data)
{
cout<<"test2"<<endl;
t->data=item;
t->next=head;
head=t;
}
else // insert in the middle or end
{
cout<<"test3"<<endl;
t= head;
node* trailt=new node;
while( item > t -> data && t != NULL )
{
cout<<"test4"<<endl;
trailt = t;
t = t -> next; // move to the next cell
if( t->next == NULL)
{
cout<<"test5"<<endl;
t->data=item;
trailt->next=t;
}
} // end while
cout<<"test6"<<endl;
t->data=item;
trailt->next=t;
t->next=t;
}
}
the code is supposed to make a linked list and when pushing number into it it checks the rest so that the numbers are inserted in numerical order from least to greatest. Not sure exactly whats causing the error
I think that on lines 44 & 45 you are failing to properly set t's next member. Even if t is inserted into the middle of the of the list, t->next is still set to t, breaking the list. I believe you would want something like:
1 2
t->next = trailt->next;
trailt->next = t;
I'm not certain how that would cause a segmentation fault, however. What line is causing the problem?
i tried but no difference in the output it completely skips past test and test 2 and then ends before printing out test 5 so it doesn't even get to lines 44 and 45
Order of evaluation is left to right; first you check if item > t->data, and THEN you check to see if t is NULL. If it was null, the first check would crash.
Aside from that, line 25 is a memory leak; there is no need to allocate a new node.