将二进制树更改为双链表的程序

Program to change binarytree to double linkedlist

本文关键字:链表 程序 二进制      更新时间:2023-10-16

我创建了一个全局对象并将其分配给 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. using namespace std是极其糟糕和危险的。永远不要这样做。该指令污染了标准库中的(通常是全局的)命名空间,其中可能有数千个名称,其中大部分您可能不知道。它们与你自己的名字产生冲突。更糟糕的是,如果您添加完全无辜且不相关的#include指令,它们可以默默地更改程序的含义
  2. 全局变量是坏的和危险的。它们经常使程序推理变得非常困难,并且几乎不可能跟踪错误。仅在需要的地方声明变量。如果需要在函数之间共享状态,请使用参数和返回值。

在您的示例中,全局变量prev与您注入全局命名空间的标准函数std::prev冲突。你本可以通过避免这两个坏习惯中的任何一个来避免错误,但这是一个忘记这两个坏习惯的好机会。不要错过它。