我正在尝试为我的数据结构讲座实现skewheap。忽略algotihm是否有效,我有代码本身的问题。在VS 2012代码运行但返回意外的结果。在调试过程中,全局变量的值(root
)意外改变。在输入Insert(1)
函数(第72行)之前,root
的值是我期望它们的值(key=5
,right=NULL
,left=NULL
)。但是当步进Insert()
时,值域会随机更改。接着,在到达线45时:意外的全局变量值;在C++中使用skewheap实现
node *p = &input;
root
变化值(input->key
,null
,null
)。在Dev C++中,该程序被关闭,其中SIGSEV
。一般sistuation看起来相似,但在Print()
中,指向left
和right
的指针将值更改为某些意外值。这是什么原因?
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
struct node
{
int key;
node* right;
node* left;
node(int _key, node* _right, node* _left)
{
key = _key;
right = _right;
left = _left;
}
};
node* root = NULL;
node* Union(node* p1, node* p2)
{
node* p;
if (!p1)
return p2;
if (!p2)
return p1;
if (p1->key > p2->key) {
p = p1;
Union(p1->right, p2);
} else {
p = p2;
Union(p1, p2->right);
}
swap(p->left, p->right);
return p;
}
void Insert(int v)
{
node input = node(v, NULL, NULL);
node* p = &input;
root = Union(root, p);
}
void Print(node* v)
{
if (!v) {
return;
}
if (v->right) {
Print(v->right);
}
cout << v->key << endl;
if (v->left) {
Print(v->left);
}
}
int main()
{
Insert(5);
Insert(1);
cout << root->key;
system("pause");
return 0;
}
我想指出的是,没有一个节点在这个程序中解脱出来,所以除非是采取照顾正在泄漏内存。在节点周围使用unique_ptr或shared_ptr可能是个好主意,除非您小心地手动删除它们。泄漏的风险很高,并且可能超过智能指针的小开销。 – 2014-12-02 07:32:39