【问题标题】:queue basic functions (put) calling (the program crashes)队列基本函数(put)调用(程序崩溃)
【发布时间】:2020-03-23 19:11:25
【问题描述】:

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

#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 函数时,程序会崩溃。我认为我调用它的方式不是很好。你能解释一下如何调用它吗?

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

【问题讨论】:

  • 当你做q.tail-&gt;succ = p 时,q.tail 指向什么? (提示:tail 未初始化)。您需要先添加第一个元素,然后才能设置其继任者
  • 顺便说一句,您在 main 中调用 InitQ() 但忽略其返回值。你的意思是写Queue q = InitQ(); 吗? (仅此一项并不能解决问题)

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


【解决方案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;
}

最后你必须在 main 中编写

Queue q = InitQ();

【讨论】:

  • 感谢您的帮助!我现在编辑了代码我想显示队列。我写了一个 PrintQ 函数来打印队列,但是当我运行程序时它显示了一些大数字然后它崩溃了.哪里出错了?
  • @DaniVaja 您不应该在已经回答后更改原始问题添加新问题。我无法重现该问题。你甚至没有复制和粘贴我展示的功能。在函数 Put 中,您没有初始化新节点。请尝试按原样复制并粘贴我显示的功能。
  • 谢谢,它工作正常,但我不知道 {x, nullptr} 在做什么
  • @DaniVaja 它初始化创建的对象。
  • 感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多