学习笔记——链表(linked list)

 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*。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值