我正在学习链接列表操作并且有一个与参数传递有关的问题。链接列表引用指针
问题1: 我正在用三个值1-> 2-> 3创建一个简单的链表。我试图打印它。 以下是我的代码。我在我的main中创建一个节点“first”,并将它传递给“createlinkedlist”方法。我正在使用一个指针“头”并在方法中更新它。但是我发现在“createlinkedlist”方法之外正确保留了“head”的值。我不明白这是怎么发生的。我想我应该使用的借鉴参数传递喜欢
void createLinkedList(struct node * & head)
或void createLinkedList(struct node ** head)
,而不是
void createLinkedList(struct node * head)
以获得正确的价值观体现在函数外。我在这里错过了什么?为什么我能够在printList方法内看到正确的值?
struct node
{
int data;
struct node * next;
};
void createLinkedList(struct node * head)
{
struct node * second = (node *)malloc(sizeof(node));
struct node * third = (node *)malloc(sizeof(node));
head->data = 1;
head->next = second;
second->data = 2;
second->next = third;
third->data = 3;
third->next = NULL;
}
void printList(struct node * first)
{
struct node * current = first;
while(current)
{
printf("%d",current->data);
current = current->next;
}
}
void main()
{
struct node * first = (node *)(malloc(sizeof(node)));
createLinkedList(first);
printList(first);
}
问题2:我使用的是同一个程序同上,但加入了推送功能
void push(struct node *& first, int data)
{
struct node * newnode = (node*)malloc(sizeof(node));
newnode->data = data;
newnode->next = first;
first = newnode;
}
现在我明白了,除非我用的是“&”在推的第一个参数( ),我无法在printList方法中看到更新。这对我来说很有意义,因为我们通常需要使用参考参数来使得在函数外部看到的局部功能改变。所以如果列表需要一个参考参数,为什么它在问题1中的行为不同。 请致电让我知道。
语言? C还是C++? – duffymo 2011-03-07 20:46:30
*和&取消。它本质上意味着[struct node head] – rkg 2011-03-07 20:48:00
@Ravi:我不认为这是一个声明的情况。 – Lars 2011-03-07 20:54:34