我正在處理鏈表的示例。但是,我目前無法理解head_insert方法。請有人解釋一下。謝謝。插入到鏈表頭時混淆了指針
#include <iostream>
using namespace std;
struct node_ll
{
int payload;
node_ll* next; // pointer to the next node
};
void head_insert(node_ll** list, int pload)
{
node_ll* temp = new node_ll;//Declare temp, a pointer to a node.
temp->payload = pload;//Set the payload of the struct at the address of temp to pload.
temp->next = *list;//Set the next of the struct at the address of temp to the pointer to the old head of the list.
*list = temp;//Set the pointer to the old head of the list to the pointer to the temp node.
//Why doesnt the temp->next = temp?
};
void print_ll(node_ll** list)
{
node_ll* temp;
temp = *list;
while (temp) // != NULL
{
cout << temp->payload << '\n';
temp = temp->next;
};
}
int main()
{
node_ll* alist = NULL;
cout << "Empty list a to start\n";
head_insert(&alist, 2);
head_insert(&alist, 4);
head_insert(&alist, 6);
cout << "List a after head insertion of 2,4,6 is \n";
print_ll(&alist);
cout << '\n';
system("PAUSE");
return 0;
}
我的困惑在評論中詳細說明。如果我有線條
temp->next = *list;
*list = temp;
爲什麼我的新創建的節點指向在明年自己的地址?
我真的不明白你的問題。沒有「清單」作爲可以「指向」任何東西的單一實體; 「列表」由*所有*節點組成。 – 2013-04-11 06:45:56
@KarlKnechtel我糾正了我的錯誤。抱歉。 – 2013-04-11 06:48:14
提示:在* * list = temp'賦值之前指向*的'* list'是什麼? – WhozCraig 2013-04-11 07:10:29