0

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.

4

2 回答 2

3

当你写

list **l;
*l=NULL;

您正在取消引用无效指针,因此遇到未定义的行为。

在函数内部,您可能传递了一个有效指针作为参数。例如

list* l;
void print(&l)

在这种情况下,&l是类型list**- 并且它指向一个 dangling list*,因此取消引用它将产生一个指针(l本身)。l未初始化,但不从中读取是可以的。

于 2013-02-19T11:57:47.340 回答
1

你写:

list **l;
*l=NULL;

但是 l 没有分配,你不知道它的值,所以 *l=NULL 是未定义的行为,因为你不知道你正在改变哪个内存区域。

于 2013-02-19T11:58:30.237 回答