简单地说,这个程序是从一个字符串创建一个字符的链表。(比如从“HELLO”到 head->h->e->l->l->o->NULL)每当我尝试使用擦除功能删除头部时,程序将停止工作,给出“application.exe已停止工作... Windows 正在检查解决方案..."。我想我的内存分配可能有问题,但我不能说清楚。建议非常感谢。
这行得通
void StringADT::append(string s)
{
for (int i = 0; i < s.length(); i++)
{
Node* NodePtr;
Node* newNode;
newNode = new Node;
newNode->data = s.at(i);
newNode->next = NULL;
if (!head)
{
head = newNode;
} else
{
NodePtr = head;
while (NodePtr->next)
{
NodePtr = NodePtr->next;
}
NodePtr->next = newNode;
}
}
}
void StringADT::erase(int pos) //pos = position to erase
{
if (!head || pos < 0 || pos > length() - 1)
return;
else {
Node* NodePtr;
NodePtr = head;
if (pos == 0)
{
NodePtr = head->next;
delete head; //PROBLEM COMES AFTER EXECUTION OF THIS LINE!!
}
}
}
这是我的课
class StringADT{
private:
struct Node {
char data;
Node* next;
};
Node* head;
这是我的附加函数,由于内存分配,它可能是问题的根源。
void StringADT::append(string s) (appending string s to the linked list)
{
Node* NodePtr;
int slength = s.length();
Node *NodeArray;
NodeArray = new Node[slength];
if(!NodeArray)
return;
for (unsigned i = 0; i < s.length(); i++)
{
NodeArray[i].data = s.at(i);
NodeArray[i].next = NULL;
}
if (!head)
{
head = NodeArray;
NodePtr = head;
for(unsigned count = 1; count < slength; count ++)
{
NodePtr->next = (NodeArray + count);
NodePtr = NodePtr->next;
//cout << "number of count " << count << endl;
}
} else {
NodePtr = head;
while (NodePtr->next)
{
NodePtr = NodePtr->next;
}
for(unsigned count = 0; count < slength; count ++)
{
NodePtr->next = (NodeArray + count);
NodePtr = NodePtr->next;
//cout << "number of count " << count << endl;
}
}
}