我在網站上找到了這個代碼,用於在列表的開頭插入一個節點到鏈表中。使用指針指向什麼點?
void push(struct Node** head_ref, int new_data)
{
/* 1. allocate node */
struct Node* new_node = (struct Node*) malloc(sizeof(struct Node));
/* 2. put in the data */
new_node->data = new_data;
/* 3. Make next of new node as head */
new_node->next = (*head_ref);
/* 4. move the head to point to the new node */
(*head_ref) = new_node;
}
這是呼叫 -
push(&head, 7);
功能我的問題是,爲什麼通過傳遞地址的指針,然後隨後在函數內部的地址提取的值走很長的路要走。 爲什麼我們不能簡單地傳遞在函數指針head
後來作出這樣的分配 -
new_node->next=head_ref;
?
[Jagged array](https://en.wikipedia.org/wiki/Jagged_array) –
因爲該函數也改變了'head_ref'的值。由於'head'有指針類型,所以你需要傳遞'push'的指針指針來更新'head'的值。 –
閱讀[this](https://stackoverflow.com/a/897400/971127) – BLUEPIXY