如何解决struct 指针如何区分相同指针的使用?
这是极客给极客的例子。最后一个示例是 root->left->left = new Node(4);
我想知道左节点如何保留其旧值,并且能够使用相同的结构变量连接到新值。每次调用“new Node()”时是创建另一个内存块还是什么?我很困惑。
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 对象,所以你有疑问
每次调用“new 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 的新节点。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。