程序将binarytree更改为双链表

时间:2019-04-14 16:26:20

标签: c++

我创建了一个全局对象并将其分配为null。当我尝试访问相同的对象时。它说是模棱两可的。我无法找到全局声明有什么问题。基本上,当它为null时,我会产生歧义。但即使我也无法执行NULL检查。

我已经编写了完整的代码。检查以下代码

using namespace std;

class node {
    public :
    int data;
    class node *left,*right;
    node(int data)
    {
        this->data=data;
        this->left=NULL;
        this->right=NULL;
    }
};
class node* head=NULL;
class node* prev=NULL;
void bt2dll(class node *tree)
{
    if(tree==NULL)
    return ;
    //static node *prev=NULL;
    bt2dll(tree->left);
    if(prev==NULL)
    head=tree;
    else
    {
        prev->right=tree;
        tree->left=head;
    }
    prev=tree;
    bt2dll(tree->right);
}
void print(node *root)  
{  
    if (root != NULL)  
    {  
        print(root->left);  
        cout<<root->data<<" ";  
        print(root->right);  
    }  
}  

void printList(node *head)  
{  
    while (head)  
    {  
        cout<<head->data<<" ";  
        head = head->right;  
    }  
}  

int main()  
{  

    node *root        = new node(10); 
    root->left        = new node(12); 
    root->right       = new node(15); 
    root->left->left  = new node(25); 
    root->left->right = new node(30); 
    root->right->left = new node(36); 

    cout << "Inorder Trvaersal of given Tree is:\n";  
    print(root);  
    bt2dll(root);  

    cout << "\nDouble Linked list is:\n";  
    printList(head);  

    return 0;  
}  
prog.cpp:23:5: error: reference to ‘prev’ is ambiguous
  if(prev==NULL)
     ^~~~
prog.cpp:16:13: note: candidates are: node* prev
 class node* prev=NULL;
             ^~~~
In file included from /usr/include/c++/6/bits/stl_algobase.h:66:0,
                 from /usr/include/c++/6/bits/char_traits.h:39,
                 from /usr/include/c++/6/ios:40,
                 from /usr/include/c++/6/istream:38,
                 from /usr/include/c++/6/sstream:38,
                 from /usr/include/c++/6/complex:45,
                 from /usr/include/c++/6/ccomplex:39,
                 from /usr/include/x86_64-linux-gnu/c++/6/bits/stdc++.h:52,
                 from prog.cpp:1:
/usr/include/c++/6/bits/stl_iterator_base_```

1 个答案:

答案 0 :(得分:3)

您的程序使两个坏习惯和危险习惯相互抵触。他们都赢了,你输了。

  1. using namespace std极其糟糕和危险。永远不要这样做。该指令污染了(通常是全局的)名称空间,而该名称空间可能来自标准库中的成千上万个名称,您可能不了解其中的大多数名称。它们与您自己的名字产生冲突。更糟糕的是,只要您添加完全无害且无关的#include指令,它们就可以静默更改程序的含义
  2. 全局变量有害且危险。他们常常使对程序的推理变得非常困难,并且几乎不可能追踪错误。仅在需要的地方声明变量。如果需要在函数之间共享状态,请使用参数和返回值。

在您的示例中,全局变量prev与注入到全局名称空间中的标准函数std::prev冲突。您可以通过避免两种不良习惯中的任何一种来避免该错误,但这是一次学习两者的好机会。不要错过。