我似乎无法弄清问题是什么,我的代码编译并运行了下面显示的有问题的函数,但是当我尝试显示所有节点的内容时,我得到了这个:
LinkedList.exe中0x50CE1F98(msvcp100d.dll)的未处理异常:0xC0000005:访问冲突读取位置0xFEEEFEEE。
//remove (and cleanup after) the node at the tail of the LinkedList (pHead)
//return a pointer to the head node
ListNode* removeEnd( ListNode* pHead )
{
ListNode* pCurr = pHead;
ListNode* pPrevPtr = NULL;
while (pCurr->pNextNode != NULL)
{
pCurr = pCurr->pNextNode;
pPrevPtr = pCurr->pNextNode;
}
pPrevPtr = NULL;
delete pCurr;
return pHead;
}
答案 0 :(得分:1)
必须是:
while (pCurr->pNextNode != NULL)
{
pPrevPtr = pCurr;
pCurr = pCurr->pNextNode;
}
答案 1 :(得分:0)
我认为应该是:
pPrevPtr = pCurr;
pCurr = pCurr->pNextNode;
不要忘记取消关联。之后简单地将pPrevPtr
设置为NULL不会影响您的列表。你可能想要:
if (pPrevPtr) pPrevPtr->pNextNode = NULL;
答案 2 :(得分:0)
while (pCurr->pNextNode != NULL)
{
pPrevPtr = pCurr;
pCurr = pCurr->pNextNode;
}
另外,为什么要返回pHead
?它是函数的参数并且不变地返回。显然你也应该取消删除已删除的节点。
delete pCurr;
if ( pPrevPtr ) pPrevPtr->pNextNode = NULL;
答案 3 :(得分:0)
您的代码有几个错误。例如,pHead可以等于NULL,或者你在这里错误地设置pPrevPtr pPrevPtr = pCurr-> pNextNode;这里pPrevPtr = NULL;
尝试以下代码。
ListNode* removeEnd( ListNode* pHead )
{
if ( pHead )
{
ListNode* pCurr = pHead;
ListNode* pPrevPtr = NULL;
while ( pCurr->pNextNode != NULL)
{
pPrevPtr = pCurr;
pCurr = pCurr->pNextNode;
}
delete pCurr;
if ( pPrevPtr ) pPrevPtr->pNextNode = NULL;
else pHead = pPrevPtr;
}
return pHead;
}