为什么创建链表时使用二级指针
提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
一、二级指针是什么
对于一级指针大家应该都很熟悉int* h, a; h = &a;
那么二级指针也很明显int* h, ** l; l = &h;
二、为什么创建链表使用二级指针
1.代码
代码如下(示例):
#include<iostream>
using namespace std;
struct node
{
int data;
node* next;
node() :next(NULL) {};
};
void create(node** h)
{
if (*h == NULL)
{
*h = new node;
}
for (int i = 0; i < 5; i++)
{
node* p = new node;
p->data = i;
p->next = (*h)->next;
(*h)->next = p;
}
}
int main()
{
node* p = NULL;
create(&p);
if (p == NULL)
{
cout << "头指针为空,创建失败" << endl;
}
else { cout << "创建成功" << endl; }
}
2.那如果不用二级指针会怎么样
代码如下(示例):
#include<iostream>
using namespace std;
struct node
{
int data;
node* next;
node() :next(NULL) {};
};
void create(node *h)
{
if (h == NULL)
{
h = new node;
}
for (int i = 0; i < 5; i++)
{
node* p = new node;
p->data = i;
p->next = (h)->next;
(h)->next = p;
}
}
int main()
{
node* p = NULL;
create(p);
if (p == NULL)
{
cout << "头指针为空,创建失败" << endl;
}
else { cout << "创建成功" << endl; }
}
总结
为什么失败了呢?因为当传递一级指针的时候只是将指针的指向的地址传递给了形参,本身未受到影响
这里p和h没有关系,因为p是空指针没东西传给h
而二级指针p将自己传给了h,所以自己指向了堆区创建的空间!
所以希望各位友友在写代码的时候注意这一点,当然如果main函数里面头指针不为空其实也可以的,但是二级指针万无一失嘛
新人博主,希望多多支持!有任何问题可以私信博主!