-1

我正在实现一个队列数据结构,但我的应用程序崩溃了。我知道我在队列类的节点指针 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");
}
4

1 回答 1

0

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

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

我的建议:

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