我正在學習鏈接列表操作並且有一個與參數傳遞有關的問題。鏈接列表引用指針
問題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