我正在编写一个涉及类中链表的程序。添加到列表中的节点将按照"优先级"按升序排序。这是随机的。当添加的节点具有按升序排列的优先级时,它可以正常工作,但是当发送的优先级按降序或有些随机时,运行时错误和崩溃结果。提供的代码导致崩溃,提供示例输出,非常感谢任何帮助
Header.h
#include <iostream>
#include <string>
using namespace std;
class CCPU {
public :
CCPU();
~CCPU();
void Process();
void AddComm(string, int);
void PrintNodes();
int length;
private :
struct NODE {
string command;
int priority;
NODE *pNext;
};
NODE *Head;
};
Functions.cpp
#include "Header.h"
CCPU::CCPU()
{
Head = NULL;
length = 0;
}
CCPU::~CCPU()
{
delete Head;
Head = NULL;
length = 0;
}
void CCPU::Process()
{
if (length != 0)
{
Head = Head->pNext;
cout << "Next command was processed!" << endl;
length--;
}
else
cout << "Cannot process next command; the list is empty!" << endl;
}
void CCPU::AddComm(string inCom, int inPri)
{
NODE *pNew = new NODE,
*pPrev = NULL,
*pCurr = Head;
pNew->command = inCom;
pNew->priority = inPri;
pNew->pNext = NULL;
while (pCurr && inPri >= pCurr->priority)
{
pPrev = pCurr;
pCurr = pCurr->pNext;
}
if (pPrev == NULL)
{
Head = pNew;
if (length != 0)
{
pNew->pNext = pCurr;
}
}
else
pPrev->pNext = pNew;
length++;
cout << "Command \"" << inCom << "\" added, with a priority of " << inPri << endl;
}
void CCPU::PrintNodes()
{
NODE *pCur = Head;
while (pCur != NULL)
{
cout << pCur->command << endl;
cout << pCur->priority << endl;
cout << endl;
pCur = pCur->pNext;
}
return;
}
Main.cpp的
#include "Header.h"
int main()
{
CCPU cpu1;
cpu1.AddComm("ADD", 4);
cpu1.AddComm("SUB", 3);
cpu1.AddComm("SUB", 2);
cpu1.AddComm("SUB", 3);
cpu1.Process();
cpu1.Process();
cpu1.Process();
cpu1.Process();
cpu1.PrintNodes();
return 0;
}
输出:
答案 0 :(得分:1)
除非您尝试研究链接列表(并且肯定不是这样),否则我建议您使用std::list
,std::forward_list
或std::priority_queue
。
您当前的代码包含很多错误。例如,在你的析构函数中,你只是通过释放头节点来泄漏内存。