c++ - 结构指针如何区分相同指针的使用?
问题描述
这是来自极客的极客示例。最后一个例子是 root->left->left = new Node(4);
我想知道左节点如何保留其旧值,并能够使用相同的结构变量连接到新值。每次调用“新节点()”时都会创建另一个内存块还是什么?我很困惑。
using namespace std;
struct Node {
int data;
struct Node* left;
struct Node* right;
// val is the key or the value that
// has to be added to the data part
Node(int val)
{
data = val;
// Left and right child for node
// will be initialized to null
left = NULL;
right = NULL;
}
};
int main()
{
/*create root*/
struct Node* root = new Node(1);
/* following is the tree after above statement
1
/ \
NULL NULL
*/
root->left = new Node(2);
root->right = new Node(3);
/* 2 and 3 become left and right children of 1
1
/ \
2 3
/ \ / \
NULL NULL NULL NULL
*/
root->left->left = new Node(4);
/* 4 becomes left child of 2
1
/ \
2 3
/ \ / \
4 NULL NULL NULL
/ \
NULL NULL
*/
return 0;
}
解决方案
root->left = new Node(2);
并且root->left->left = new Node(4);
都在内存中创建新的 Node 对象,所以你有问题
每次调用“新节点()”时都会创建另一个内存块还是什么?
有点准确。
最初,root 是一个 Node 对象,其数据值为 1,左值为 NULL。它的左指针指向任何东西。该语句root->left = new Node(2);
将根左指针设置为新节点的地址。这个新节点的数据值为 2,左值为 NULL。想象一下这个新节点有一个名字,它的名字是 A。表达式root->left->left
从左到右计算root->left
,节点 A 也是,因此表达式变为A->left
。 A->left
当前为 NULL。执行完root->left->left = new Node(4);
A 的左指针现在指向一个数据值为 4 的新节点。
推荐阅读
- javascript - 在 youtube.com 上获取所有 DOM 元素
- python - 在python中发送多个cookie
- httpclient - HttpClient 不返回所有标头
- c# - C# 通过 Z 数之间的较大距离拆分坐标数组
- react-native - 对象作为 React 子对象无效(关于 firebase)
- python - 递归以在 Python 中使用单个 like if else 打印前十个数字的总和
- amazon-web-services - 在 AWS-IoT 中使用 http 创建事物 api?
- c++ - 使用按引用传递的 C++ 中的奇怪行为?
- jquery - 数组删除\t\n。--NodeJS--
- javascript - Javascript滚动总是在底部