c++ - 链表数据访问

标签 c++ linked-list binary-search-tree singly-linked-list

在 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/

相关文章:

java - 顺时针旋转链表

c - 在 C 中反转双链双端队列

c# - 打开 URL 的自定义图标

c++ - 关闭句柄/存储句柄

c++ - 完成处理程序中的 Boost 绑定(bind)错误

c - 单行打印中序树遍历的数据,以空格分隔,以换行符结尾

c++ - 二叉搜索树中的节点拒绝删除

C++ 如何触发类析构函数

java - 我的代码中出现错误如何修复?

在二叉搜索树中查找小于给定值的所有值的算法