反转传递指针地址的链表

时间:2013-05-26 22:52:56

标签: c list pointers linked-list malloc

typedef struct slist *LInt;

typedef struct slist{

int value;
LInt next;
}Node;

void reverse(LInt *l){

LInt tail;
if(*l){
    tail=(*l)->next;
    reverse(&tail);
    snoc(&tail,(*l)->value);
    free(*l),
    *l=tail;
    }
}

在main上,我调用这样的函数:reverse(& l); (l是“LInt l”),snoc的作用是将值放在列表的最后一个链接上。

我的问题是,为什么我们在调用函数时必须通过“l”的地址?为什么在反向标题上,有“LInt * l”?它是指向我通过的地址的指针吗?

如果这是一个愚蠢的问题我很抱歉,如果我犯了任何语法错误(英语不是我的母语)。

提前谢谢。

2 个答案:

答案 0 :(得分:0)

答案1(为什么我们在调用函数时必须传递“l”的地址?)

函数reverse()可以更改原始列表。但是函数的非数组输入是inputs,它们是按值传递的。它们不会影响原始l。因此,要更改l,请将地址传递给reverse()。这允许reverse()更改l,因为它知道l存在的位置。

答案2(为什么在反向标题上,有“LInt * l”?)

请参阅答案1. reverse需要知道LInt类型的地址才能影响更改。

示例:

int x,y;   // 2 non-array variables.
y = f(x);  // X does not change.  You expect y to change.
g(&x);     // After g() is done, the value of x may have changed.
           // Of course, the _address_ of x, being what you passed to g(), did not change.

答案 1 :(得分:0)

您将typedef LInt定义为POINTER TO STRUCTURE

    typedef struct slist *LInt;            

这就是为什么你没有指定'next'作为下一个LInt;结构。

如果您将typedef定义为

    typedef struct slist LInt;

然后传递参数LInt * l有效。你正在传递结构指针。

Typedef是为了帮助您创建小的UNDERSTANDABLE数据类型(同义词不是新的)

考虑这样定义:

   typedef struct slist LIST;  //i prefer this mostly
   typedef struct slist * LIST_PTR; 

因此,当您定义新列表时,它不会让您感到困惑。

   LIST *head;  //creating a pointer - Head of linkedlist
   LIST_PTR head;