链接列表数据访问

时间:2012-09-25 05:07:51

标签: 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; 
    }

此外,有时我看到链接列表节点为子节点使用*节点,有时他们只使用节点。何时/为什么要使用其中之一。很抱歉字符串问题很好奇。

1 个答案:

答案 0 :(得分:3)

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

例如,如何执行此操作:

/* 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!
}