【问题标题】:Implementation of priority queue using linked list使用链表实现优先级队列
【发布时间】:2020-05-01 19:07:15
【问题描述】:
#include<iostream>
using namespace std;

//template<class T>
class Node
{
    public:
//  T data;
    int data;
    Node *next;
    int priority;
};

//template<class T>
class Que
{
        Node *front , *rear;
    public:
        Que(){front = rear = NULL;}

//      void enqueue(T x);
//      T dequeue();
        void enqueue(int *x, int l);
        int dequeue();
        void display();
};

//template<class T>
//void Que<T>::enqueue(T x)
void Que::enqueue(int *x, int l)
{
    Node * pt = front;
    for(int i=0; i<l; i++){
    Node *t = NULL;
    t = new Node;
    if(t==NULL)
        cout<<"Queue is full"<<endl;
    else
    {
        t->next = NULL;
        t->data = x[i];
        t->priority = x[i];
        if(front==NULL)
            front = rear =t;
        else
        {
            if(front->priority <= t->priority)
            {
                t->next = front;
                front = t;
            }
            else
            {
                while(pt->next!= NULL && pt->next->priority <= x[i])
                    pt = pt->next;
                t->next = pt->next;
                pt->next = t;
            }
        }
    }
}
}

//template<class T>
//T Que<T>::dequeue()
int Que::dequeue()
{
//  T x = -1;
    int x = -1;
    Node *t = NULL;
    if(front == NULL)
        cout<<"Queue is empty"<<endl;
    else
    { 
        x = front->data;
        t = front;
        front = front->next;
        delete t;
    }
    return x;
}

//template<class T>
//void Que<T>::display()
void Que::display()
{
    Node *t = front;
    while(t)
    {
        cout<<t->data<<" ";
        t = t->next;
    }
    cout<<endl;
}

int main()
{
//  Que <int> q();
    Que q;
    int a [] = {6, 1, 2, 5, 4, 3};
    q.enqueue(a, sizeof(a)/sizeof(a[0]));
//  q.dequeue();
    q.display();
    return 0;
}

这是在 C++ 中使用链表的优先级队列代码。 enqueue 成员函数内的 while 循环显示分段错误。

我认为指向用于指向前面的节点的指针 *pt 没有正确指向。我一直在尝试解决它,但不知道。这可能是什么原因?

【问题讨论】:

  • 是时候调试自己的代码了
  • 如果你将优先级队列与链表分开——围绕链表而不是在链表内部构建优先级队列——你可以测试和调试更小、更简单的代码块时间。
  • 嗨,欢迎来到 Stack Overflow。请阅读stackoverflow.com/help/how-to-ask。特别是关于在您将代码转储给我们之前描述问题的部分。
  • 调试此类问题的最佳方法是在调试器中单步执行代码。如果您不知道如何使用调试器,那么现在是学习的最佳时机。它将为您节省无数小时的调试时间。此外,围绕链表构建优先级队列的建议也不错。
  • 除了使用调试器,还可以画图。没有什么可以帮助您理解图形问题,即使是像链表这样的简单图形,也不能像可视化它一样。画出清单。画出您需要执行的所有步骤,以便在列表上执行所需的操作。调试时按照图纸进行。当你看到程序做的不是你画的东西时,你发现了一个错误,你可能知道该怎么做。

标签: c++ data-structures linked-list queue


【解决方案1】:

您在enqueue 的开头初始化pt,但从未在循环中重置它。因此,当您将多个元素添加到空列表时,pt 将以nullptr 开头,并且在将第一个元素添加到列表后不会更新。当您尝试将第二个元素添加到列表中时,您取消引用 pt-&gt;next 这会导致您的分段错误,因为 pt 仍然是 nullptr

修复很简单:将Node * pt = front; 移动到 for 循环。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-14
    • 2017-02-08
    • 2014-01-19
    • 1970-01-01
    相关资源
    最近更新 更多