插入元素时,C ++ Priority Queue崩溃

时间:2014-01-31 10:48:15

标签: c++ crash nodes priority-queue

我通过Min Heap编制了一个优先级队列。 这是指向PriorityQueue类的Node指针。

当我尝试通过PriorityQueue创建vector对象时效果很好。问题是通过Node方法单独插入指向Insert 的指针。它也可以工作并打印优先级队列,但有时它会在执行结束时崩溃!它返回错误尽管效果很好

输出:

a 1
b 2
c 3


Process returned -1073741819 (0xC0000005)   execution time : 3.000 s
Press any key to continue.

主:

int main()
{
    NODE a = new Node('a',1);
    NODE b = new Node('b',2);
    NODE c = new Node('c',3);

    Q.Insert(a);
    Q.Insert(b);
    Q.Insert(c);

    Q.Print();

    return 0;
}

Node代码:

typedef class Node *NODE;

class Node {
private:
    unsigned char Ch;
    int Key;
    NODE L;
    NODE R;
public:
    Node() { L = NULL; R = NULL; };
    Node(int, unsigned char, NODE, NODE);
    Node(unsigned char, int);
    ~Node() { delete L; delete R; };
    NODE Left();
    NODE Right();
    int GetKey();
    unsigned char GetChar();
    void SetKey(int);
    void SetChar(unsigned char);
};

Node::Node(unsigned char c, int k)
{
    Ch = c; Key = k; R = NULL; L = NULL;
}

NODE Node::Left()
{
    return L;
}

NODE Node::Right()
{
    return R;
}

unsigned char Node::GetChar()
{
    return Ch;
}

int Node::GetKey()
{
    return Key;
}

void Node::SetKey(int k)
{
    Key = k;
}

PriorityQueue代码:

class PriorityQueue {
private:
    vector<NODE> A;
    int Heap_Size;
    int Parent(int);
    int Left(int);
    int Right(int);
    void Swap(NODE &, NODE &);
    void MinHeapify(int);
public:
    PriorityQueue();
    PriorityQueue(vector<NODE>);
    ~PriorityQueue() {};
    NODE Minimum();
    NODE ExtractMin();
    void DecreaseKey(int, int);
    void Insert(NODE);
    bool IsEmpty();
    void Print();
};

PriorityQueue::PriorityQueue()
{
    // I need to push back an empty node to use the vector from the index 1.
    // This is important to move in the min-heap trough the indices.
    NODE Default = new Node;
    A.push_back(Default);

    Heap_Size = 0;
}

PriorityQueue::PriorityQueue(vector<NODE> vett)
{
    A = vett; Heap_Size = A.size()-1;

    for (int i=Heap_Size/2; i>=1; i--)
    {
        MinHeapify(i);
    }
}

void PriorityQueue::Swap(NODE &a, NODE &b)
{
    NODE temp = a;
    a = b;
    b = temp;
}

void PriorityQueue::DecreaseKey(int i, int key)
{
    if (key > A[i]->GetKey())
    {
        cout << "How can I decrease the key?" << endl;
        return;
    }

    A[i]->SetKey(key);

    while (i>1 && A[Parent(i)]->GetKey() > A[i]->GetKey())
    {
        Swap(A[i],A[Parent(i)]);
        i = Parent(i);
    }
}

void PriorityQueue::Insert(NODE Nodo)
{
    Heap_Size++;
    A[Heap_Size] = Nodo;
    DecreaseKey(Heap_Size,Nodo->GetKey());
}

void PriorityQueue::Print()
{
    for (int i=1; i<=Heap_Size; i++)
        cout << A[i]->GetChar() << " " << A[i]->GetKey() << endl;
}

非常感谢!!!!

1 个答案:

答案 0 :(得分:0)

我解决了!问题是:

Heap_Size++;
A[Heap_Size] = Nodo;

A是vector,因此我必须以这种方式进行编辑:

A.push_back(Nodo);