我有一个名为 StringList 的类,它具有多个管理和操作字符串链接列表的函数。我有一个 AddtoTop,它添加到列表的顶部,AddtoBottom,一个名为 add 的函数,它添加一个字符串但按字母顺序放置它,一个 clear 函数,一个 find 函数,一个 print 和一个 remove 函数。我已经编写了每一个函数,但是我有一个主要问题。当我使用“AddtoTop”和“AddtoBottom”时,我将一个字符串添加到链接列表中。当我要求删除仅使用这两个函数放置的字符串时,我的删除函数起作用。当我尝试删除使用“添加”功能添加的单词时,我的程序崩溃了。函数“remove”(如下所示)可以删除使用“AddtoBottom”和“AddtoTop”添加的字符串 函数,但不是使用“add”添加的字符串 谁能帮我找出原因?我试图以不同的方式重新编写它,但我被卡住了。这是我的功能:
StringList::StringList() //constructor
{
pTop=NULL;
pBottom=NULL;
}
StringList::~StringList() //destructor
{
StringListNode *next;
for (StringListNode *sp = pTop; sp != 0; sp = next)
{
next = sp->pNext;
delete sp;
}
}
void StringList::add(string s) //adds and places in alphabetical order
{
if(pTop)
{
if( s < pTop->data )
{
StringListNode *A=new StringListNode;
A->data = s;
A->pNext = pTop;
pTop = A; // new top
return;
}
// go further into list
StringListNode *iter = pTop;
while( iter->pNext )
{
if( iter->pNext->data < s )
iter = iter->pNext;
else
break;
}
StringListNode *in=new StringListNode; //actuallly inserts node
in->data = s;
in->pNext = iter->pNext;
iter->pNext = in;
}
else// new item
{
pTop = new StringListNode;
pTop->data = s;
pTop->pNext = NULL;
}
}
StringList::StringListNode *StringList::find(const string &s) //basic search function
{
StringListNode *sp = pTop; // Search
while (sp != 0 && sp->data != s)
sp = sp->pNext;
return sp;
}
void StringList::addToTop(string s) //add to top of nodes
{
if(isEmpty())
{
StringListNode * pNewNode;
pNewNode = new StringListNode;
(*pNewNode).data = s;
pTop=pNewNode;
pBottom=pNewNode;
(*pNewNode).pPrev = NULL;
(*pNewNode).pNext = NULL;
}
else //it's not empty
{
StringListNode * pNewNode;
pNewNode = new StringListNode;
(*pNewNode).data = s;
(*pNewNode).pNext = pTop;
(*pTop).pPrev = pNewNode;
(*pNewNode).pPrev =NULL;
pTop=pNewNode;
}
}
void StringList::addToBottom(string s) // add to bottom
{
if(isEmpty())
{
StringListNode * pNewNode;
pNewNode = new StringListNode;
(*pNewNode).data = s;
pTop=pNewNode;
pBottom=pNewNode;
(*pNewNode).pPrev = NULL;
(*pNewNode).pNext = NULL;
}
else
{
StringListNode * pNewNode;
pNewNode = new StringListNode;
(*pNewNode).data = s;
(*pBottom).pNext = pNewNode;
(*pNewNode).pPrev = pBottom;
(*pNewNode).pNext =NULL;
pBottom=pNewNode;
}
}
string StringList::print() //prints strings in linked list
{
string result;
StringListNode * pCurrent;
pCurrent=pTop;
while(pCurrent!=NULL)
{
result+=(*pCurrent).data+"\n";
pCurrent=(*pCurrent).pNext;
}
return result;
}
void StringList::clear() //clears everything
{
pTop = NULL;
pBottom = NULL;
}
void StringList::remove(string s) //removes a string
{
StringListNode *curr = this->find(s);
if (curr->pPrev != 0)
curr->pPrev->pNext = curr->pNext;
if (curr->pNext != 0)
curr->pNext->pPrev = curr->pPrev;
if (pTop == curr)
pTop = curr->pNext;
if (pBottom == curr)
pBottom = curr->pPrev;
}