gpt4 book ai didi

c++ - 创建队列类时出错

转载 作者:行者123 更新时间:2023-11-30 03:03:27 25 4
gpt4 key购买 nike

我正在尝试创建一个简单的 Queue 类。现在我卡住了。它几乎完成了。我发现只有一个函数“pop”导致了这个问题。谁能告诉我我该怎么做。

代码如下:
(队列.h)

#ifndef  _QUEUE_
#define _QUEUE

#include <iostream>
#include <string>
using namespace std;


struct Stuff
{
string name;
int roll;
};


class Queue
{
private:

struct Node
{
Stuff data ;
struct Node * next;
};
Node *front;
Node *back;
int qsize;
const int MAX;
public:

Queue(int size = 5);
~Queue();

bool isfull() const;
bool isempty() const;
int queuesize() const;

bool push(const Stuff & item);
bool pop();
Stuff first();
Stuff last();


};




#endif

队列.cpp

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

Queue::Queue(int size)
:MAX(size)
{
front = back = 0;
qsize = 0;

}
bool Queue::isempty() const
{
if(qsize == 0)
return true;
else return false;
}
bool Queue::isfull() const
{
if(qsize == MAX)
return true;
else
return false;
}
Queue::~Queue()
{
Node * temp;
while(front != NULL)
{
temp = front;
front = front->next;
delete temp;
}

}
int Queue::queuesize() const
{
return qsize;
}

bool Queue::push(const Stuff & swag)
{
if( isfull() )
return false;

Node *add = new Node;

if(add == NULL)
return false;
add->data = swag;
add->next = NULL;

if(front == NULL)
front = add;
else
back->next = add->next;
back = add;
qsize++;

return true;
}


bool Queue::pop()
{
if(isempty() )
return false;
if(front == NULL)
return false;
Node *temp =front;


// I think this part is doing something wrong.
front = front->next;



delete temp;
qsize--;
if(qsize == 0)
back = NULL;
return true;

}
Stuff Queue::first()
{
return front->data;
}
Stuff Queue::last()
{
return back->data;
}

主要.cpp

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

int main()
{
Queue a(5);
Stuff data;
data.name = "icp";
data.roll= 755;
a.push(data);
Stuff x = a.last();

cout << x.name << "\t" << x.roll << endl;
data.name = "sms";
data.roll= 12544;
a.push(data);
x = a.last();
cout << x.name << "\t" << x.roll << endl;

data.name = "jmc";
data.roll= 98740;
a.push(data);
x = a.last();
cout << x.name << "\t" << x.roll << endl;

cout << a.queuesize() << endl;

/////////////
x = a.first();
cout << x.name << "\t" << x.roll << endl;
a.pop();

x = a.first();
cout << x.name << "\t" << x.roll << endl;
a.pop();

x = a.first();
cout << x.name << "\t" << x.roll << endl;
a.pop();


////
cin.get();
cin.get();
return 0;
}

程序在弹出第一个元素后崩溃。我已经指出了我认为有问题的部分。提前致谢:)

最佳答案

我认为问题出在推送功能上。以下代码

if(front == NULL)
front = add;
else
back->next = add->next;

back->next 设置为add->next,为NULL。 add->next = NULL;

add 是下一个要返回的,所以它应该是 back->next = add;

你认为pop函数的问题是因为front为NULL,所以front->next是错误的。

希望对您有所帮助。

关于c++ - 创建队列类时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9349230/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com