我正在处理一个链表示例。但是,我目前无法理解 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;
为什么我新创建的节点在 next 中没有指向它自己的地址?