【问题标题】:Queue Data structure app crash with front() method使用 front() 方法的队列数据结构应用程序崩溃
【发布时间】:2012-11-19 10:55:21
【问题描述】:

我正在实现一个队列数据结构,但我的应用程序崩溃了。我知道我在队列类的节点指针 front 或 Front() 方法上做错了

#include <iostream>
using namespace std;

class Node 
{ 
    public: 
        int get() { return object; }; 
        void set(int object) { this->object = object; }; 
        Node * getNext() { return nextNode; }; 
        void setNext(Node * nextNode) { this->nextNode = nextNode; }; 
    private: 
        int object; 
        Node * nextNode; 
};

class queue{
    private:
        Node *rear;
        Node *front;
    public:
        int dequeue() 
        { 
            int x = front->get(); 
            Node* p = front; 
            front = front->getNext(); 
            delete p; 
            return x; 
        }

        void enqueue(int x) 
        { 
            Node* newNode = new Node(); 
            newNode->set(x); 
            newNode->setNext(NULL); 
            rear->setNext(newNode); 
            rear = newNode; 
        }

        int Front() 
        { 
            return front->get(); 
        } 

        int isEmpty() 
        { 
            return ( front == NULL ); 
        }
};
main()
{
    queue q;
    q.enqueue(2);
    cout<<q.Front();

    system("pause");
}

【问题讨论】:

  • 写完代码之后,接下来要做的就是调试了。您可以使用调试器,也可以添加打印语句来跟踪其行为。这是每个程序员都需要具备的技能。混过去,逐渐缩小问题的范围。你会开始掌握它的窍门,下次它会更快。

标签: c++ data-structures queue crash


【解决方案1】:

您多次使用未初始化的指针。

  • 入队指的是后方->setNext()。如果队列为空,则后端未初始化,导致崩溃。
  • Front 通过某个节点成员函数返回节点,而不检查非空指针。为什么不简单地返回 *front 指针?
  • 您的所有类都没有构造函数。您的指针甚至不是 NULL 指针,它们只是未初始化。这是自找麻烦。

我的建议:

  • 给这两个类一个构造函数。
  • 调用任何节点成员函数时,检查有效指针。
  • 使用更少的节点成员函数;尽可能返回原始指针。

【讨论】:

  • 不工作我初始化构造函数错误吗? queue::queue() { 后方=NULL;前面=空; }
  • 缺少构造函数并不是唯一的问题。您仍在取消引用空指针。确保每个函数都检查空队列(甚至出队!)。
  • @Garminic 我发现我的 enque() 方法不正确,你能解决它吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多