指针字段在C ++中的行为不符合预期

时间:2016-10-05 07:27:04

标签: c++ pointers binary-search-tree

以下是我无法导致错误的示例代码。

#include<iostream>
using namespace std;
struct node
{
    int value;
    node* left;
    node* right;
    node* parent;

    node()
    {
    }

    node(int value)
    {
        this->value = value;
        this->left = NULL;
        this->right = NULL;
        this->parent = NULL;
    }
};



int coun = 0;

void check(node** root)
{
    if(coun == 0)
    {
        coun++;
        check(&((*root)->right));
    }

    else
    {

        node *parentOfCurrent,*childOfCurrent;
        parentOfCurrent = (*root)->parent;
        childOfCurrent = (*root)->right;
        cout << "Value before the statement" << (*root) << "\n";
        parentOfCurrent->right = childOfCurrent;
        cout << "Value after the statement" << (*root) << "\n";
    }
}



int main()
{
    node *node1,*node2,*node3,*node4,**temp,*temp2;
    node1 = new node(1);
    node2 = new node(2);
    node3 = new node(3);
    cout << "Node1 Node2 Node3" << node1 << " " << node2 << " " << node3 << "\n";
    node1->right = node2;
    node2->right = node3;
    node2->parent = node1;
    node3->parent = node3;

    check(&node1);

    //cout << node2->value;
}

在这个例子中,我创建了一个树as descibed here 我在这里尝试将node1的右侧字段分配给node3。 我遵循的程序是:

  • 1)将node1的地址(双指针)传递给功能检查。
  • 2)因为coun = 0,所以它增加到coun = 1,然后再次调用 这次传递了node2的地址。
  • 3)在此调用中声明

parentOfCurrent->right = childOfCurrent; 被执行。

此语句旨在将node1的.right字段分配给node3。发生的事情是声明不同之前和之后的*值。

Value before the statement: 0x9e17b8
Value after the statement: 0x9e6f30

正在发生的是指针 parentOfCurrent-&gt;右边(* root)被设置为childOfCurrent ,但我无法解释为什么发生这种情况?

1 个答案:

答案 0 :(得分:1)

你有这个“树”:

  1 
 /\
x  2
   /\
  x  3

当您输入递归时,root保存1右指针的地址。

  1 
 /\
x  2  <-- *root (root == &node1->right)
   /\
  x  3

parentOfCurrent->right指向1的正确孩子(其值与*root相同)。
childOfCurrent指向3节点。

分配后,root仍然是1右指针的地址,但1的右子项现在是3节点:

  1 
 /\
x  3  <-- *root (root == &node1->right)
   /\
  x  x

这里似乎没有双指针间接 试试这个:

void check(node* root)
{
    if(coun==0)
    {
        coun++;
        check(root->right);
    }
    else
    {   
        node *parentOfCurrent, *childOfCurrent;
        parentOfCurrent = root->parent;
        childOfCurrent = root->right;
        cout<<"Value before the statement"<<root<<"\n";
        parentOfCurrent->right = childOfCurrent;
        cout<<"Value after the statement"<<root<<"\n";
    }
}

int main()
{
    node *node1,*node2,*node3;
    node1 = new node(1);
    node2 = new node(2);
    node3 = new node(3);
    cout<<"Node1 Node2 Node3"<<node1<<" "<<node2<<" "<<node3<<"\n";
    node1->right = node2;
    node2->right = node3;
    node2->parent = node1;
    node3->parent = node2;  // You had a bug here, making node3 its own parent. 
    check(node1);
    cout << node1->right->value; // Prints 3
}

请注意,您还需要调整正在移动的节点的父指针,但我将其删除了。

相关问题