1. 单链表
插入
struct Node
{
int data;
Node* next; //指向节点的指针
};
Node* head; //全局变量 指向头地址的指针
void Insert(int data)
{
Node* temp1 = new Node; //用指针写入
temp1->data = data;
temp1->next = NULL;
Node* temp2 = head;
if (temp2 == NULL)
head = temp1;
else
{
while (temp2->next != NULL)
{
temp2 = temp2->next;
}
temp2->next = temp1;
}
}
Q:为什么不在函数中直接定义节点?
Node* Insert(int x)
{
Node temp; //直接定义
temp->data = x;
temp->next = NULL;
return &temp;
}
而是用指针指向地址定义?
void Insert(int x)
{
Node* temp=new Node; //引用指针
temp->data = x;
temp->next = NULL;
}
A:变量存储区
因为在函数段中定义的节点为<局部变量>(local variable),局部变量存储在stack,当该函数调用完成,会被从stack中删除。所以,即使返回了在stack中创建的地址&temp,此时该地址也没有节点了,因为函数调用完成后的stack中删除是自动发生的。
而使用指针指向<全局变量>(global variable)时,全局变量存储在heap,一直存储在内存中,除非我们明确将其删除,可被任何函数调用。
PS:对于heap中创建的东西,我们不能使用直接名称。访问heap的唯一方法是通过指针,即Node*。