【发布时间】:2015-03-12 16:21:22
【问题描述】:
我无法理解关于使用双指针的链表的 C 代码的含义。这是我正在阅读的代码
struct list
{
int value;
struct list *next;
};
//Insert an element at the begining of the linked list
void insertBegin(struct list **L, int val)
{
//What does **L mean?
//Memory allocation for the new element temp
struct list *temp;
temp = (struct list *)malloc(sizeof(temp));
//The new element temp points towards the begining of the linked list L
temp->next = *L;
//Set the beginning of the linked list
*L = temp;
(*L)->value = val;
}
void loop(struct list *L)
{
printf("Loop\n");
//Run through all elements of the list and print them
while( L != NULL )
{
printf("%d\n", L->value);
L = L->next;
}
}
struct list* searchElement(struct list *L,int elem)
{
while(L != NULL)
{
if(L->value == elem)
{
printf("Yes\n");
return L->next;
}
L = L->next;
}
printf("No\n");
return NULL;
}
int main()
{
struct list *L = NULL;
insertBegin(&L,10); // Why do I need
return 0;
}
insertElement 中的**L 是什么意思,**L 和loop 函数中的*L 有什么区别?为什么在声明 struct list *L = NULL 时,我应该使用参数 &L 而不是简单的 L 来调用函数 insertBegin?
我猜*L 是指向链表第一个节点的指针,而**L 可能指向链表的任何元素。但是,我不确定这是否正确。
感谢您的帮助!
【问题讨论】:
-
temp = (struct list *)malloc(sizeof(temp));-->temp = malloc(sizeof *temp);
标签: c linked-list double-pointer