Write a program to reverse the direction of a given singly-linked list. In other words, after the reversal all pointers should now point backwards.
I am trying to solve above problem. I wrote functions for insertion,search and deletion and printing for the singly linked list.
my print function is as follows
void print(list **l)
{
list *p=*l;
for(int i=0;p;i++)
{
cout<<p->item<<endl;
p=p->next;
}
}
it works fine printing all values in the list.
but in the main function if I do the same assignment like this
list *p=*l;
it gives me segmentation fault. my main function is as follow
main()
{
list **l;
*l=NULL;
int n;
while(cin>>n)
insert(l,n);
list *p=*l;
list *prev=NULL;
list *next;
while(p)
{
next=p->next;
p->next=prev;
prev=p;
if(next==NULL)
*l=p;
p=next;
}
print(l);
}
my insert function is as follows
void insert(list **l,int x)
{
list *p;
p=(list *)malloc(sizeof(list));
p->item=x;
p->next=*l;
*l=p;
}
what is the difference between the assignment I do in print function and the main function? why I don't get any error in print function and I get a segmentation fault in the main function?
if my function is like this
main()
{
list **l;
*l=NULL;
int n;
while(cin>>n)
insert(l,n);
print(l);
}
I am not getting any error I am able to insert and print values of the list.