队列基本功能(放入)调用(程序崩溃)

问题描述 投票:1回答:1

所以我写了一些基本的操作来学习队列。问题是,当我运行程序时,它崩溃了,我不知道为什么。代码:标头

#ifndef HEADER_H_
#define HEADER_H_

typedef int Atom;
struct Element {
    Atom info;
    Element* succ;
};

struct Queue {
    Element *head, *tail;
};

Queue InitQ(void);
bool IsEmpty(Queue q);
void Put(Queue& q, Atom x);
Atom Get(Queue& q);
void PrintQ(Queue q);

#endif 

功能

#include <iostream>
#include "header.h"
using namespace std;

Queue InitQ(void)
{
    Queue q;
    q.head = q.tail = 0;
    return q;
}

bool IsEmpty(Queue q)
{
    if (q.head == NULL && q.tail == NULL)
        return true;
    else
        return false;
}

void Put(Queue& q, Atom x)
{
    Element *p = new Element;

    if (q.head == nullptr)
    {
        q.head = q.tail = p;
    }
    else
    {
        q.tail = q.tail->succ = p;
    }
}

Atom Get(Queue& q)
{
    Element* p = q.head;
    int aux;
    aux = p->info;
    q.head = p->succ;
    if (q.head == nullptr) q.tail = nullptr;
    delete(p);
    return aux;
}

void PrintQ(Queue q)
{
    if (IsEmpty(q))
    {
        cout << "Empty queue";
    }
    else
    {
        Element* p = q.head;
        while (p != NULL)
        {
            cout << p->info << " ";
            p = p->succ;
        }

    }
}

主文件

#include <iostream>
#include "header.h"
using namespace std;

int main()
{
    Queue q=InitQ();
    Put(q,2);
    Put(q, 3);
    Put(q, 7);
    PrintQ(q);
    Get(q);
    PrintQ(q);
    return 0;
}

当我调用程序的Put函数时,它会崩溃。我认为我没有很好地调用它。您能解释如何调用它吗?

编辑:我编辑了代码,现在程序显示了一些大数字然后粉碎了。我在做什么错呢?

c++ data-structures memory-management queue
1个回答
1
投票

函数IsEmpty应该声明为

bool IsEmpty( const Queue &q )
{
    return q.head == nullptr;
}

功能Put无效。队列为空时未设置指针头。可以通过以下方式定义函数

void Put( Queue& q, Atom x)
{
    Element *p = new Element { x, nullptr };

    if ( q.head == nullptr )
    {
        q.head = q.tail = p;
    }
    else
    {
        q.tail = q.tail->succ = p;
    }
}

函数Get应该至少像这样定义

Atom Get(Queue& q)
{
    Element* p = q.head;
    int aux;
    aux = p->info;
    q.head = p->succ;
    if ( q.head == nullptr ) q.tail = nullptr;
    delete(p);
    return aux;
}

最后主要是您必须写

Queue q = InitQ();
© www.soinside.com 2019 - 2024. All rights reserved.