我正在尝试从分配中的链接列表中删除节点,并且遇到一个我不知道如何解决的错误。
这是我的班级
class PhoneList
{
public:
PhoneList(string/*name*/);
~PhoneList();
void showList(ostream&/*file/screen*/) const;
friend void showList(ostream&/*file/screen*/, PhoneList/*List*/);
void addDirectory(string/*name*/, int/*areaCode*/, int/*phoneNo*/);
void removeDirectory(string/*name*/);
int getNoDirectories()const { return noDirectories; }
string getTitle()const { return title; }
private:
Directory *firstPtr;
string title;
int noDirectories;
};
这是我的目录结构
struct Directory
{
string name;
int areaCode;
int phoneNo;
Directory *link;
};
这是我的删除功能
void PhoneList::removeDirectory(string delName)
{
Directory *walker = NULL;
Directory *stalker = NULL;
Directory *placeHolder = NULL;
walker = firstPtr;
stalker = NULL;
while (walker != NULL)
{
if (walker->name == delName)
{
break;
}
else
{
stalker = walker;
walker = walker->link;
}
}
if (walker == NULL)
{
cout << "Contact not found. Removal not possible. Please enter valid contact name." << endl;
}
else
{
stalker = walker;
walker = walker->link;
delete stalker;
cout << "Contact Deleted." << endl;
}
}
这是我正在使用的客户端代码
myBlackBook->removeDirectory("Adam Taurus");
myBlackBook->removeDirectory("Xander Rogan");
myBlackBook->removeDirectory("Johnathan Jones");
myBlackBook->removeDirectory("Johnathan Jones");
myBlackBook是我创建的一个电话清单对象,三个名称在列表中,是的,第四个是第三个的重复。我需要证明错误消息能够正确触发。
我已调试,第一个delete函数调用正确进行,但是下一次firstPtr和walker对象将名称成员显示为“错误读取字符串字符”。 我尝试了多种方法来解决此问题,并且这种情况一直在发生。谢谢您的帮助。
答案 0 :(得分:2)
在遍历任何链表时,您需要测试处理以下情况:
我不确定您的删除功能正在处理上述情况2。否则,我希望在删除列表的开头时看到代码更新firstPtr
。
void PhoneList::removeDirectory(const string& delName)
{
Directory *walker = firstPtr;
Directory* previous = NULL;
bool found = false;
if (firstPtr)
{
while (walker && !found)
{
if (walker->name == delName)
{
if (walker == firstPtr)
{
// handle the special case of deleting from the front
firstPtr = firstPtr->link;
}
else
{
previous->link = walker->link;
}
delete walker;
found = true;
}
else
{
previous = walker;
walker = walker->link;
}
}
}
if (found)
{
cout << "Contact Deleted." << endl;
}
else
{
cout << "Contact not found." << endl;
}
}