c++ - 排队基本功能(放入)调用(程序崩溃)

标签 c++ data-structures memory-management queue

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

#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函数时,它会崩溃。我认为我不好用它来调用它。您能解释一下如何调用它吗?

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

最佳答案

函数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();

关于c++ - 排队基本功能(放入)调用(程序崩溃),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60820116/

相关文章:

java - 获得所有资源的完整释放,如 System.exit(0) 中所示

java - 如何计算Java程序的内存使用量?

c++ - C中的多行宏

c++ - 如何通过 .props 文件设置调试符号路径

c++ - 添加索引为 -2 的整数

python - 如何根据列值合并数据框中的行?

algorithm - 红黑树 - K 插入和 K 删除所需的最大旋转次数?

java - 在 Java 中分配大量相对较小的对象

c++ - 密集对称矩阵的特征有效类型

c++ - 如何在事件窗口之外进行C++输入?