gpt4 book ai didi

c++ - 链表数据访问

转载 作者:行者123 更新时间:2023-11-28 00:53:52 26 4
gpt4 key购买 nike

在 C++ 中,如果我有以下形式的二叉搜索树 (BST)

Struct node{ 
node leftChild;
node rightChild;
int data;}

像这样访问 leftChild 数据是否合法:

foo (node head)
{
std::cout << head.leftChild.data;
}

此外,有时我看到链表节点使用 *node 作为子节点,而其他时候他们只使用 node。你什么时候/为什么要使用其中之一。抱歉,字符串问题只是好奇。

最佳答案

不,因为你不能有那样的结构。它会无限大(一个 node 有两个子 node,每个子 node 都有两个子 node,等等)。这正是人们在创建具有相同类型子节点的节点时使用指针的原因。

例如,如何去做:

/* This is a problem because of the recursive nature of the structure. leftChild also
contains a leftChild itself, which also contains a leftChild, etc. forever. */
struct node
{
node leftChild; // how big is leftChild? infinitely large!
node rightChild; // how big is rightChild? infinitely large!
int data;
}

正确的方法:

/* This is not a problem because the size of a pointer is always 4 bytes (assuming 32-
bit system). You can allocate room for the child nodes without recursively requiring an
infinite amount of memory. */
struct node
{
node* leftChild; // how big is leftChild? 4 bytes (assuming 32-bit system)
node* rightChild; // how big is rightChild? 4 bytes (assuming 32-bit system)
int data;
}

一旦您以正确的方式进行操作,就可以完全合法地说:

void foo(node head)
{
std::cout << head.leftChild->data; // assuming leftChild points to a valid object!
}

关于c++ - 链表数据访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12576479/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com