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

丹妮·瓦哈(DaniVaja)

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

#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();

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

Haskell基本功能

来自分类Dev

cljc文件的基本功能

来自分类Dev

获取python基本功能列表

来自分类Dev

在Haskell中创建基本功能

来自分类Dev

基本功能帮助-Python

来自分类Dev

对象返回中的基本功能

来自分类Dev

JavaScript使用变量的基本功能

来自分类Dev

基本功能的奇怪行为

来自分类Dev

AngularJS中的基本功能

来自分类Dev

对象返回中的基本功能

来自分类Dev

C ++需要基本功能的指导

来自分类Dev

JavaScript:后退/前进的基本功能

来自分类Dev

Unity基本功能说明

来自分类Dev

基本功能N cov / contravariance

来自分类Dev

MATLAB中的基本功能

来自分类Dev

球拍基本功能列表

来自分类Dev

mangoose 加入 mangodb 的基本功能?

来自分类常见问题

Laravel 4帮助程序和基本功能的最佳实践?

来自分类Dev

Behat SpecBDD和StoryBDD基本功能symfony2示例应用程序

来自分类Dev

如何解决 Azure 基本功能应用程序错误

来自分类Dev

该功能是否覆盖基本功能?

来自分类Dev

与基本功能同名的球拍宏功能

来自分类Dev

WordPress功能可为管理面板创建基本功能

来自分类Dev

Gradle项目同步失败的基本功能

来自分类Dev

R的基本功能中的表观异常

来自分类Dev

如果我包含jQuery,则找不到基本功能

来自分类Dev

哪些R版本包含哪些基本功能

来自分类Dev

如何使用“ CImg”及其基本功能

来自分类Dev

使用Matlab中的基本功能重建图像