提问者:小点点

分段错误,在这段代码中,使用这段代码创建了一个使用链表[关闭]的队列


给出的代码打印1 0 12然后显示分段错误,尝试了很长时间来解决这个问题,但没有发现错误,请帮助:我没有看到分段错误的原因,一直在尝试用链表实现队列,尝试使用不同的编译器,但没有帮助。在给定的代码中,如果可能的话,请找出错误,并告诉我如何改进这段代码


#include<iostream>
using namespace std;
class Node
{
    public:
        int data;
        Node *next;
        Node(int n)
        {
            data=n;
            next=NULL;
        }
};
class queueLinked
{
    int count;
    Node* head;
    Node* tail;
    public:
        queueLinked()
        {
            count=0;
            head=NULL;
        }
        int size()
        {
            return count;
        }
        bool empty()
        {
            return count==0;
        }
        int front()
        {
            if(head==NULL)
            {
                cout<<"EMPTY QUEUE";
                return 0;
            }
            return head->data;
        }
        void enqueue(int a)
        {
            Node *temp=new Node(a);
            if(head==NULL)
            {
                head=temp;
                tail=temp;
                count=1;
                return;
            }
            tail->next=temp;
            tail=tail->next;
            count++;
        }
        void dequeue()
        {
            if(head=NULL)
            {
                cout<<"EMPTY QUEUE"<<endl;
                return;
            }
            Node *temp=head;
            head=head->next;
            delete temp;
            count--;
        }
};
int main()
{
    queueLinked a;
    a.enqueue(12);
    cout<<a.size()<<endl;
    cout<<a.empty()<<endl;
    a.enqueue(13);
    cout<<a.front()<<endl;
    a.dequeue();
    cout<<a.front()<<endl;
    a.dequeue();
    a.dequeue();
    cout<<a.empty()<<endl;
    cout<<a.size()<<endl;
    cout<<a.front()<<endl;
}

共1个答案

匿名用户

您的代码几乎是正确的它缺少了“==”条件,还有一点您应该将head->移动到temp旁边,否则当您删除head时,关于下一个节点的所有信息也将被删除。

void dequeue()
    {
        if (head == NULL)
        {
            cout << "EMPTY QUEUE" << endl;
            return;
        }
        // Node* temp = head;
        
        Node* temp = head->next;
        delete head;
        head = temp;
        count--;
    }