链表SIGSEGV,分段错误



我用链表做了一个练习题(我想多练习一下(,我得到了以下错误

程序接收到信号SIGSEGV,分段故障。0x0000555555555888在主.cpp的LinkedList::getLink(this=0x0(中:24 24返回链接;

我不知道这个方法有什么问题,因为回顾过去我写的东西,它们似乎和这个一样。

#include<iostream>
#include<string>
class LinkedList{
char sign;
int count;
LinkedList *link;
public:
LinkedList(char sign) : sign(sign),count(1),link(nullptr) {}
inline void Increment()
{
count++;
}
inline int getCount() const
{
return count;
}
inline void setLink(LinkedList *whereTo)
{
link=whereTo;
}
inline LinkedList* getLink() const
{
return link;
}
inline char getSign() const
{
return sign;
}
};
void stringInput(std::string &var)
{
std::cout<<"Enter some text:";
std::getline(std::cin,var);
}
unsigned int factorial(unsigned int n)
{
return (n!=0)? n*factorial(n-1) : 1;
}
void addList(char sign,LinkedList *&start,LinkedList *&helper,LinkedList *&end)
{
end=new LinkedList(sign);
if(start==nullptr)
{
start=end;
}
else
{
helper->setLink(end);
}
helper=end;
}
bool isInList(char sign,LinkedList *helper)
{
while(helper!=nullptr)
{
if(sign==helper->getSign())
{
helper->Increment();
return true;
}
helper=helper->getLink();
}
return false;
}
void addSignsToList(const std::string &var,LinkedList *&start,LinkedList *&helper,LinkedList *&end)
{
for(int i=0;i<var.size();i++)
{
if(!isInList(var[i],start))
{
addList(var[i],start,helper,end);
}
}
}
void freeLinkedLists(LinkedList *start)
{
LinkedList *helper=start->getLink();
while(start!=nullptr)
{
delete start;
start=helper;
helper=helper->getLink();
}
}
unsigned int factorialSum(LinkedList *helper)
{
unsigned int sum=1;
while(helper!=nullptr)
{
sum*=factorial(helper->getCount());
helper=helper->getLink();
}
return sum;
}
unsigned int comb(const std::string &var)
{
LinkedList *start=nullptr,*helper=nullptr,*end=nullptr;
addSignsToList(var,start,helper,end);
unsigned int upperHalf=factorial(var.size());
double lowerHalf=factorialSum(start);
freeLinkedLists(start);
return upperHalf/lowerHalf;
}
int main()
{
std::string var;
stringInput(var);
std::cout<<"The word ""<<var<<"" has "<<comb(var)<<" possible combinations!n";
std::cin.get();
return 0;
}

在中

void freeLinkedLists(LinkedList *start)
{
LinkedList *helper=start->getLink(); // fails immediately if start is null
while(start!=nullptr)
{
delete start;
start=helper;
helper=helper->getLink(); // too late. Helper may already be null. 
// This won't be  spotted until start is 
// tested on the next loop iteration 
}
}

而是使用

void freeLinkedLists(LinkedList *start)
{
while(start!=nullptr) // handles empty list case
{
LinkedList *helper=start->getLink(); // get next node while we know 
// current node is valid
delete start;
start=helper; // may be null and will be caught by the while
}
}

相关内容

  • 没有找到相关文章

最新更新