我用纯 C 语言做到了,但现在我正在尝试在 C++ 中实现一个二叉搜索树。大多数代码完全相同,但我想使用 new
运算符而不是malloc()
。但是,我收到此错误:
Undefined symbols for architecture x86_64:
"operator new(unsigned long)", referenced from:
GetNewNode(int) in BstTreeV3-beb469.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
这是我在 ideone 上的代码。单击此处查看。
Node* GetNewNode(int data) {
Node *newNode = new Node();
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
void Insert(Node **root, int data)
{
if (*root == NULL) { // empty tree
*root = GetNewNode(data);
}
else if ((*root)->data < data) {
Insert(&((*root)->left), data);
}
else {
Insert(&((*root)->right), data);
}
}
我知道这可能不是最好的实现方法,但我只是在练习。如果您对如何实施BST有任何建议,请随时发表评论。
为了使程序有意义,它应该是这样的:
class Node
{
private:
int data;
Node* left;
Node* right;
public:
Node()
:data(0), left(NULL), right(NULL)
{}
Node(int d)
:data(d), left(NULL), right(NULL)
{}
};
...
*root = new Node(data);
如果你不使用这些语言功能,你不妨坚持使用 C。
尽管您遇到的特定错误很可能来自使用 C 编译器编译C++代码,正如您的问题评论中所指出的那样。